package o2o.web.actions.order.admin;

import com.alibaba.fastjson.JSON;
import com.jinyou.utils.common.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import o2o.cache.agent.AgentManagerMemory;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.order.*;
import o2o.cache.order.admin.AdminOrderMemoryMan;
import o2o.cache.order.admin.AgentOrderMemoryMan;
import o2o.cache.order.shop.ShopOrderMemoryMan;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.config.properties.ConfigProperties;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.AgentManagerInfo;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.order.*;
import o2o.dao.PO.postman.POSTMAN_TYPE;
import o2o.dao.PO.shop.SHOP_IS_INTEGRAL;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.order.OrderInfoAdminVO;
import o2o.dao.VO.order.OrderInfoVO;
import o2o.dao.VO.order.OrderPostmanTroubleVO;
import o2o.dao.VO.user.UserInfoVO;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.system.data.SYS_SOS_MODEL_TYPE;
import o2o.task.order.OrderBakTaskUtils;
import o2o.web.actions.company.SysCityCompanyMan;
import o2o.web.actions.order.OrderListMan;
import o2o.web.actions.order.OrderMan;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static o2o.web.actions.order.OrderMan.getOrderDetail;


//管理员订单管理
@Controller
public class AdminOrderListController {

    @Autowired
    private ConfigProperties configProperties;

    // 管理员 -》 线路 -》 骑手
    private static ConcurrentHashMap<String, ConcurrentHashMap<Long, Set<String>>> dataMap = new ConcurrentHashMap<>();

    //-----------------------------管理员

    /**
     * 获取商家未确认的订单 管理员
     */
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/shop/not/sure/list")
    @ResponseBody
    public String order_admin_not_sure_list(String token, Integer orderType, String city, String county, String region,
                                            Integer isCityAgent,  // 是否按代理获取 0否 1是
                                            Long agentId,         // 代理id
                                            Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //是否有权限抢单
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }

        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }

        List<OrderInfo> orderList = null;
        if (UserType.ADMIN == user.getUserType()) {
            boolean isNoCount = false;
            if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
                switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                    case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                        return AjaxResult.successResult(null, 0);
                    }
                    case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                        isNoCount = true;
                    }
                    break;
                }
            }
            // 城代
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("  FROM ")
                    .append(PojoTables.OrderInfo).append(" a ")
                    .append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append("  b ON a.agentId = b.agentId ")
//                    .append(" LEFT JOIN ").append(PojoTables.SHOP_AGENT_RELATION).append(" c ON b.agentId= c.agentId ")
                    .append(" WHERE a.delFlag = 0 AND b.delFlag =0 ")
                    .append(" AND  b.username = '").append(user.getUsername()).append("' ");

            if (SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE != null && SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE == 1) {
                stringBuffer.append(" AND a.orderType != ").append(ORDER_TYPE.GROUP_ORDER);
            } else {
                if (null != orderType) {
                    stringBuffer.append(" AND a.orderType = ").append(orderType);
                } else {
                    stringBuffer.append(" AND a.orderType != ").append(ORDER_TYPE.GROUP_ORDER);
                }
            }
            if (ValidateUtil.isID(agentId)) {
                stringBuffer.append(" and a.agentId =").append(agentId);
            }
            long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
            if (ValidateUtil.isAbsLong(pointTime)) {
                stringBuffer.append(" and a.createTime > ").append(pointTime);
            }

            StringBuffer sbSelect = new StringBuffer();
            sbSelect.append(" select a.createTime,a.orderNo ");
            sbSelect.append(stringBuffer.toString());
            sbSelect.append(" and a.orderStatus = ").append(ORDER_STATUS.PAYED);
            sbSelect.append(" union ");
            sbSelect.append(" select a.createTime,a.orderNo ");
            sbSelect.append(stringBuffer.toString());
            sbSelect.append(" and a.orderStatus = ").append(ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP);
            sbSelect.append(" union ");
            sbSelect.append(" select a.createTime,a.orderNo ");
            sbSelect.append(stringBuffer.toString());
            sbSelect.append(" and a.orderStatus = ").append(ORDER_STATUS.ARRIVE_PAY);
            sbSelect.append(" union ");
            sbSelect.append(" select a.createTime,a.orderNo ");
            sbSelect.append(stringBuffer.toString());
            sbSelect.append(" and a.orderStatus = ").append(ORDER_STATUS.UNDERLINE_SUBMIT);
            sbSelect.append(" ORDER BY createTime DESC ");

            StringBuffer sbCount = new StringBuffer();
            sbCount.append(" SELECT a.orderNo ");
            sbCount.append(stringBuffer.toString());
            sbCount.append(" and a.orderStatus = ").append(ORDER_STATUS.PAYED);
            sbCount.append(" union ");
            sbCount.append(" SELECT a.orderNo ");
            sbCount.append(stringBuffer.toString());
            sbCount.append(" and a.orderStatus = ").append(ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP);
            sbCount.append(" union ");
            sbCount.append(" SELECT a.orderNo ");
            sbCount.append(stringBuffer.toString());
            sbCount.append(" and a.orderStatus = ").append(ORDER_STATUS.ARRIVE_PAY);
            sbCount.append(" union ");
            sbCount.append(" SELECT a.orderNo ");
            sbCount.append(stringBuffer.toString());
            sbCount.append(" and a.orderStatus = ").append(ORDER_STATUS.UNDERLINE_SUBMIT);

            long totalCount = 0l;
            try {
                if (!isNoCount) {
                    StringBuffer sbB = new StringBuffer();
                    sbB.append("SELECT  count(b.orderno) counts from (").append(sbCount.toString());
                    sbB.append(" ) b");
                    totalCount = UserDaoSql.getInstance().getCount(sbB.toString());
                }

                if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                    StringBuffer sbA = new StringBuffer();
                    sbA.append("SELECT ").append(selectFiled).append(" from (").append(sbSelect.toString());
                    sbA.append(" ) b");
                    sbA.append(" left join ").append(PojoTables.OrderInfo).append(" a on a.orderNo = b.orderNo ")
                            .append(" where a.id is not null ");
                    sbA.append(" limit ").append((page - 1) * size).append(",").append(size);
                    orderList = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbA.toString());
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            if (ValidateUtil.isAbsList(orderList)) {
                return AjaxResult.successResult(orderList, totalCount);
            }

        } else {
            String sysCityAdminUsername = user.getUsername();
            Set<Long> agentIdSet = null;
            if (user.getUserType() == UserType.AGENT_MANAGER) {
                AgentManagerInfo info = AgentManagerMemory.getInstance().get(user.getUsername());
                if (info == null) {
                    return AjaxResult.successResult(null, 0);
                }
                List<CityAgent> cityAgents = CityAgentMemory.getInstance().listByAgentManagerUsername(user.getUsername());
                if (!ValidateUtil.isAbsList(cityAgents)) {
                    return AjaxResult.successResult(null, 0);
                }
                agentIdSet = cityAgents.stream().map(b -> b.getId()).collect(Collectors.toSet());
            } else if (UserType.COMPANY == user.getUserType() && SysCityCompanyMan.isAdminCompanyUser(sysCityAdminUsername)) {
                sysCityAdminUsername = SysCityCompanyMan.getSysCompanyOwnUsername(sysCityAdminUsername);
                if (ValidateUtil.isNull(sysCityAdminUsername)) {
                    return AjaxResult.errorResult("代理信息为空");
                }
            }

            if (user.getUserType() == UserType.AGENT_MANAGER) {
                if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
                    switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                        case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                            return AjaxResult.successResult(null, 0);
                        }
                    }
                }
                StringBuilder sql = new StringBuilder();
                sql.append(" select * from ").append(PojoTables.OrderInfo)
                        .append(" where delFlag = 0 and agentId in (").append(StringUtils.join(agentIdSet, ",")).append(") ");
                if (orderType != null) {
                    sql.append(" and orderType = ").append(orderType);
                }
                if (ValidateUtil.isNotNull(city)) {
                    sql.append(" and (city like '%").append(city).append("%' or  shopCity like '%").append(city).append("%' )");
                }
                if (ValidateUtil.isNotNull(county)) {
                    sql.append(" and county like '%").append(county).append("%' ");
                }
                sql.append(" and ( orderStatus =").append(ORDER_STATUS.PAYED).append(" or  orderStatus =").append(ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP)
                        .append(" or  orderStatus =").append(ORDER_STATUS.ARRIVE_PAY)
                        .append(" or  orderStatus =").append(ORDER_STATUS.UNDERLINE_SUBMIT)
                        .append(" ) ").append(" order by createTime desc");
                try {
                    orderList = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sql.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                orderList = AdminOrderMemoryMan.listOfShopNotSure(city, county, region, orderType, isCityAgent, sysCityAdminUsername);
            }
            if (ValidateUtil.isAbsList(orderList) && ValidateUtil.isID(agentId)) {
                orderList = orderList.stream().filter(b -> ValidateUtil.isID(b.getAgentId()) && agentId - b.getAgentId() == 0).collect(Collectors.toList());
            }
            //获取该城市订单
            JYPageUtils.PageList pageList = JYPageUtils.getList(orderList, page, size);
            if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
                List<OrderInfoVO> orderInfoVOList = new ArrayList<OrderInfoVO>();
                for (int i = 0; i < pageList.list.size(); i++) {
                    if (null == pageList.list.get(i)) {
                        continue;
                    }

                    OrderInfoVO orderInfoVO = new OrderInfoVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(pageList.list.get(i), orderInfoVO, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    if (null == orderInfoVO) {
                        continue;
                    }
                    if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                        orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                    }
                    orderInfoVOList.add(orderInfoVO);
                }
                return AjaxResult.successResult(pageList.totalCount, orderInfoVOList.size(), orderInfoVOList);
            }
        }


        return AjaxResult.successResult(0, 0, null);
    }

    //获取指定下的所有订单 管理员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/status/list")
    @ResponseBody
    public String order_admin_confirm_pay(String token, Integer orderStatus, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //是否是管理员
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        if (orderStatus == null) {
            return AjaxResult.errorResult("订单装填不能为空");
        }
        // 线下支付订单
        List<OrderInfo> orderInfoList = OrderInfoMemoryMan.getListOrderByOrderStatus(orderStatus);
        // 排序
        if (orderInfoList != null && orderInfoList.size() > 0) {
            Collections.sort(orderInfoList, new Comparator<OrderInfo>() {
                @Override
                public int compare(OrderInfo o1, OrderInfo o2) {
                    if (o1 != null && o2 != null) {
                        if (o1.getCreateTime() < o2.getCreateTime()) {
                            return 1;
                        } else if (o1.getCreateTime() > o2.getCreateTime()) {
                            return 0;
                        }
                    }
                    return 0;
                }
            });
        }
        JYPageUtils.PageList pageList = JYPageUtils.getList(orderInfoList, page, size);

        if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
            List<OrderInfoVO> orderInfoVOList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < pageList.list.size(); i++) {
                if (null == pageList.list.get(i)) {
                    continue;
                }

                OrderInfoVO orderInfoVO = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(pageList.list.get(i), orderInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoVO) {
                    continue;
                }
                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
//                    orderInfoVO.setShopImageUrl(Common.imageUrl + orderInfoVO.getShopImageUrl());
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }
                orderInfoVOList.add(orderInfoVO);
            }
            return AjaxResult.successResult(pageList.totalCount, orderInfoVOList.size(), orderInfoVOList);
        }
        return AjaxResult.successResult(0, 0, null);
    }

    private final String selectFiled = " a.id,a.orderNo,a.parentOrderNo,a.orderType,a.dispatchState,a.username,a.rePayUsername,a.orderStatus,a.shopId,a.squareShopId,a.shopName,a.totalCount,a.totalPrice,a.totalWeight,a.isPaid,a.payType,a.payType2,a.payTime,a.isRefundApply,a.isPartCancelApply,a.groupState,a.isGroupOrder,a.isZiQu,a.ziQuTime,a.postmanUsername,a.note,a.shopCity,a.agentId,a.buyer,a.telephone,a.lat,a.lng,a.province,a.city,a.county,a.address,a.address2,a.shopPhone,a.shopSelfPost,a.shopSureBySys,a.postmanSureBySys,a.postmanName,a.postmanPhone,a.preDayNo,a.isAppointment,a.isArrivePay,a.isSpecifiedPostmen,a.isComment,a.shopImageUrl,a.shopAddress,a.shopLat,a.shopLng,a.postmanImageUrl,a.isSeriesSaleShop,a.secondaryPostManUsername,a.secondaryPostmanName,a.secondaryPostmanPhone,a.secondaryPostmanImageUrl,a.secondaryPostmanSureTime,a.secondaryPostmanPullTime,a.postmanPostPointTime,a.payOrderNo,a.refundNo,a.isBackStock,a.postmanFinishTime,a.postFailReason,a.createTime ";

    //获取进行中的订单  管理员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/ing/list")
    @ResponseBody
    public String order_admin_ing_list(String token, Integer orderType, String city, Long agentId, String county, String region,
                                       @RequestParam(defaultValue = "0") Integer isGroupOrder,
                                       Integer isCityAgent, //   //是否按代理获取 0否 1是
                                       Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        //验证是否有权限
        if (!User.hasServiceAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }


        List<OrderInfo> list = null;
        Long totalCount = 0l;
        if (UserType.ADMIN == user.getUserType()) {
            // 城代
            StringBuffer sb = new StringBuffer();
            sb.append(" FROM ").append(PojoTables.OrderInfo).append(" a ")
                    .append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append("  b ON a.agentId = b.agentId ")
                    //.append(" LEFT JOIN ").append(PojoTables.SHOP_AGENT_RELATION).append(" c ON b.agentId= c.agentId ")
                    .append(" WHERE a.delFlag = 0 AND b.delFlag =0 ")
                    .append(" and (a.orderStatus!='").append(ORDER_STATUS.OVER).append("' and a.orderStatus!='").append(ORDER_STATUS.CANCEL)
                    .append("' and a.orderStatus!='").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append("' and a.orderStatus!='").append(ORDER_STATUS.PAYED_CANCEL)
                    .append("' and a.orderStatus!='").append(ORDER_STATUS.SHOP_REFUSED).append("' and  a.orderStatus!='").append(ORDER_STATUS.SUBMIT)
                    .append("' and  a.orderStatus!='").append(ORDER_STATUS.PAYED)
                    .append("' ) ")
                    .append(" AND  b.username = '").append(user.getUsername()).append("' ");
            //.append(" AND c.delFlag = 0  AND c.id IS NOT NULL ");
            long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
            if (ValidateUtil.isAbsLong(pointTime)) {
                sb.append(" and  a.createTime > ").append(pointTime);
            }
            if (ValidateUtil.isID(agentId)) {
                sb.append(" and a.agentId =").append(agentId);
            }

            if (SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE != null && SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE == 1) {

            } else {
                if (null != orderType) {
                    sb.append(" AND a.orderType = ").append(orderType);
                } else {
                    if (isGroupOrder == 1) {
                        sb.append(" and a.orderType = ").append(ORDER_TYPE.GROUP_ORDER);
                    } else {
                        sb.append(" and a.orderType != ").append(ORDER_TYPE.GROUP_ORDER);
                    }
                }
            }

            sb.append(" ORDER BY a.createTime DESC ");
            try {
                if (!isNoCount) {
                    StringBuffer sbB = new StringBuffer();
                    sbB.append("SELECT count(a.orderno) counts ").append(sb.toString());
                    totalCount = UserDaoSql.getInstance().getCount(sbB.toString());
                }

                if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                    StringBuffer sbA = new StringBuffer();
                    sbA.append("SELECT ")
                            .append(selectFiled)
                            .append(sb.toString());
                    sbA.append(" limit ").append((page - 1) * size).append(",").append(size);
                    list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbA.toString());
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            String cityStr = "";
            if (ValidateUtil.isNotNull(city)) {
                if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                    if (JYPinyinHelper.isChinese(city)) {
                        city = JYPinyinHelper.toHanyuPinyin(city);
                    } else {
                        city = city.toLowerCase();
                    }
                }
                cityStr = " and (shopCity='" + city + "' or city = '" + city + "')";
            }
            if (ValidateUtil.isNotNull(county)) {
                cityStr += " and (county='" + county + "')";
            }
            String shopIdStr = "";
            if (user.getUserType() == UserType.AGENT_MANAGER) {
                // 区域管理
                AgentManagerInfo info = AgentManagerMemory.getInstance().get(user.getUsername());
                if (info == null) {
                    return AjaxResult.successResult(null, 0);
                }
                List<CityAgent> cityAgents = CityAgentMemory.getInstance().listByAgentManagerUsername(user.getUsername());
                if (!ValidateUtil.isAbsList(cityAgents)) {
                    return AjaxResult.successResult(null, 0);
                }
                Set<Long> agentIdSet = cityAgents.stream().map(b -> b.getId()).collect(Collectors.toSet());
                shopIdStr = " and agentId in (" + StringUtils.join(agentIdSet, ",") + ") ";
            } else if (null != isCityAgent && isCityAgent - 1 == 0) {
                // 获取城市代理下所有店铺
                String shopIds = "";
                List<Long> shopIdListlist = OrderListMan.getShopIdList(user.getUsername());
                if (ValidateUtil.isAbsList(shopIdListlist)) {
                    shopIds = (JSON.toJSONString(shopIdListlist)).replace("[", "").replace("]", "");
                    if (ValidateUtil.isNotNull(shopIds)) {
                        shopIdStr = " and shopId in(" + shopIds + ")";
                    }
                }
            }
            if (SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE != null && SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE == 1) {
                // 自定义的订单类型
                StringBuffer sb = new StringBuffer();
                sb.append(" from ").append(PojoTables.OrderInfo).append(" where delFlag = 0 ").append(cityStr).append(shopIdStr)
                        .append(" and  (orderStatus!='").append(ORDER_STATUS.OVER).append("' and orderStatus!='").append(ORDER_STATUS.CANCEL)
                        .append("' and orderStatus!='").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append("' and orderStatus!='").append(ORDER_STATUS.PAYED_CANCEL)
                        .append("' and orderStatus!='").append(ORDER_STATUS.SHOP_REFUSED).append("' and  orderStatus!='").append(ORDER_STATUS.SUBMIT)
                        .append("' and  orderStatus!='").append(ORDER_STATUS.PAYED)
                        .append("' and  orderStatus!='").append(ORDER_STATUS.ARRIVE_PAY)
                        .append("' and  orderStatus!='").append(ORDER_STATUS.UNDERLINE_SUBMIT)
                        .append("' ) ")
                        .append(" and (LEFT(orderNo,1) = 'M' or LEFT(orderNo,1) = 'P' or LEFT(orderNo,1) = '1'or LEFT(orderNo,1) = '2' or LEFT(orderNo,1) = '3' or LEFT(orderNo,1) = '4'  or LEFT(orderNo,1) = '5') ")
                        .append(" ORDER BY isUrgent desc,createTime DESC ");
                try {
                    StringBuffer sbSql = new StringBuffer();
                    sbSql.append("select * ").append(sb.toString()).append(" LIMIT ").append((page - 1) * size).append(",").append(size);
                    list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());

                    StringBuffer sbCount = new StringBuffer();
                    sbCount.append("select count(1) counts ").append(sb.toString());
                    totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult("查询失败，请稍后再试");
                }

                if (ValidateUtil.isAbsList(list)) {
                    List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
                    if (ValidateUtil.isAbsList(voList)) {
                        return AjaxResult.successResult(totalCount, voList.size(), voList);
                    }
                }
            }

            String orderTypeStr = "";
            if (null == orderType) {
                orderTypeStr = " and orderStatus != " + ORDER_STATUS.SUBMIT;
            } else {
                if (0 == ORDER_TYPE.SERVICE_LOCK - orderType) {
                    //如果是开锁订单
                    orderTypeStr += " and orderStatus != " + ORDER_STATUS.PAYED;
                    orderTypeStr += " and orderStatus != " + ORDER_STATUS.SUBMIT;
                    orderTypeStr += " and orderStatus != " + ORDER_STATUS.POSTMAN_CANT_FINISH;
                }
                orderTypeStr += " and orderType = " + orderType;
            }


            //v2
            if (isGroupOrder == 1) {
                orderTypeStr += " and orderType = " + ORDER_TYPE.GROUP_ORDER;
            } else {
                orderTypeStr += " and orderType != " + ORDER_TYPE.GROUP_ORDER;
            }
            StringBuffer sb = new StringBuffer();
            sb.append(" from ").append(PojoTables.OrderInfo).append(" where delFlag = 0 ").append(cityStr).append(shopIdStr)
//                    .append(" and  createTime > ").append(OrderMan.getDefaultQueryOrderTimePoint())
                    .append(orderTypeStr).append(" and  (orderStatus!='").append(ORDER_STATUS.OVER).append("' and orderStatus!='").append(ORDER_STATUS.CANCEL)
                    .append("' and orderStatus!='").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append("' and orderStatus!='").append(ORDER_STATUS.PAYED_CANCEL)
                    .append("' and orderStatus!='").append(ORDER_STATUS.SHOP_REFUSED).append("' and  orderStatus!='").append(ORDER_STATUS.SUBMIT)
                    .append("' and  orderStatus!='").append(ORDER_STATUS.PAYED)
                    .append("' and  orderStatus!='").append(ORDER_STATUS.ARRIVE_PAY)
                    .append("' and  orderStatus!='").append(ORDER_STATUS.UNDERLINE_SUBMIT)
                    .append("' ) ")
                    .append(" and (LEFT(orderNo,1) = 'M' or LEFT(orderNo,1) = 'P' or LEFT(orderNo,1) = '1'or LEFT(orderNo,1) = '2' or LEFT(orderNo,1) = '3' or LEFT(orderNo,1) = '4'  or LEFT(orderNo,1) = '5') ")
            ;
            if (ValidateUtil.isID(agentId)) {
                sb.append(" and agentId =").append(agentId);
            }
            long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
            if (ValidateUtil.isAbsLong(pointTime)) {
                sb.append(" and createTime > ").append(pointTime);
            }
            sb.append(" ORDER BY isUrgent desc,createTime DESC ");

            try {
                if (!isNoCount) {
                    StringBuffer sbCount = new StringBuffer();
                    sbCount.append("select count(1) counts ").append(sb.toString());
                    totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
                }

                if (totalCount > 0 || isNoCount) {
                    StringBuffer sbSql = new StringBuffer();
                    sbSql.append("select * ").append(sb.toString()).append(" LIMIT ").append((page - 1) * size).append(",").append(size);
                    list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
                }
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("查询失败，请稍后再试");
            }
        }


        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, totalCount);
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }


    //获取已完成的订单  管理员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/finish/list")
    @ResponseBody
    public String order_admin_finish_list(String token, Integer orderType, Long agentId, String city, String county, String region,
                                          @RequestParam(defaultValue = "0") Integer isGroupOrder,
                                          Long startTime, Long endTime,
                                          Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        //验证是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        List<OrderInfo> list = null;
        Long totalCount = 0l;
        if (user.getUserType() == UserType.ADMIN) {
            // 城代
            StringBuffer sb = new StringBuffer();
            sb.append(" FROM ").append(PojoTables.OrderInfo).append(" a ")
                    .append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append("  b ON a.agentId = b.agentId ")
                    //.append(" LEFT JOIN ").append(PojoTables.SHOP_AGENT_RELATION).append(" c ON b.agentId= c.agentId ")
                    .append(" WHERE a.delFlag = 0 AND b.delFlag =0 ")
                    .append(" and a.orderStatus = ").append(ORDER_STATUS.OVER)
                    .append(" AND  b.username = '").append(user.getUsername()).append("' ");
            //.append(" AND c.delFlag = 0  AND c.id IS NOT NULL ");
            if (ValidateUtil.isID(agentId)) {
                sb.append(" and a.agentId =").append(agentId);
            }
            if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
                sb.append(" and a.createTime  BETWEEN  ").append(startTime).append(" and  ").append(endTime);
            } else {
                long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
                if (ValidateUtil.isAbsLong(pointTime)) {
                    sb.append(" and  a.createTime > ").append(pointTime);
                }
            }

            if (SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE != null && SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE == 1) {

            } else {
                if (null != orderType) {
                    sb.append(" AND a.orderType = ").append(orderType);
                } else {
                    if (isGroupOrder == 1) {
                        sb.append(" AND a.orderType = ").append(ORDER_TYPE.GROUP_ORDER);
                    } else {
                        sb.append(" AND a.orderType != ").append(ORDER_TYPE.GROUP_ORDER);
                    }
                }
            }

            sb.append(" ORDER BY a.id DESC ");
            try {
                if (!isNoCount) {
                    StringBuffer sbB = new StringBuffer();
                    sbB.append("SELECT count(a.orderno) counts ").append(sb.toString());
                    totalCount = UserDaoSql.getInstance().getCount(sbB.toString());
                }


                if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                    StringBuffer sbA = new StringBuffer();
                    sbA.append("SELECT ")
                            .append(selectFiled)
                            .append(sb.toString());
                    sbA.append(" limit ").append((page - 1) * size).append(",").append(size);
                    list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbA.toString());
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

        } else {
            String agentStr = "";
            //
            if (user.getUserType() == UserType.AGENT_MANAGER) {
                // 区域管理
                AgentManagerInfo info = AgentManagerMemory.getInstance().get(user.getUsername());
                if (info == null) {
                    return AjaxResult.successResult(null, 0);
                }
                List<CityAgent> cityAgents = CityAgentMemory.getInstance().listByAgentManagerUsername(user.getUsername());
                if (!ValidateUtil.isAbsList(cityAgents)) {
                    return AjaxResult.successResult(null, 0);
                }
                Set<Long> agentIdSet = cityAgents.stream().map(b -> b.getId()).collect(Collectors.toSet());
                agentStr = " and agentId in (" + StringUtils.join(agentIdSet, ",") + ") ";
            }

            String orderTypeStr = "";
            if (SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE != null && SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE == 1) {

            } else {
                if (null == orderType) {
                    if (isGroupOrder == 1) {
                        orderTypeStr += " and orderType = " + ORDER_TYPE.GROUP_ORDER;
                    } else {
                        orderTypeStr += " and orderType != " + ORDER_TYPE.GROUP_ORDER;
                    }
                } else {
                    if (0 == ORDER_TYPE.SERVICE_LOCK - orderType) {
                        //如果是开锁订单
                        orderTypeStr += " and orderStatus != " + ORDER_STATUS.PAYED;
                    }
                    orderTypeStr += " and orderType = " + orderType;
                }
            }


            String cityStr = "";
            if (ValidateUtil.isNotNull(city)) {
                if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                    if (JYPinyinHelper.isChinese(city)) {
                        city = JYPinyinHelper.toHanyuPinyin(city);
                    } else {
                        city = city.toLowerCase();
                    }
                }
                cityStr = " and (shopCity='" + city + "' or city = '" + city + "')";
            }
            if (ValidateUtil.isNotNull(county)) {
                cityStr += " and (county='" + county + "')";
            }
//            if (isGroupOrder == 1) {
//                orderTypeStr += " and orderType = " + ORDER_TYPE.GROUP_ORDER;
//            } else {
//                orderTypeStr += " and orderType != " + ORDER_TYPE.GROUP_ORDER;
//            }

            StringBuffer sb = new StringBuffer();
            sb.append(" from ").append(PojoTables.OrderInfo).append(" a where delFlag = 0 ").append(cityStr).append(orderTypeStr).append(agentStr)
                    .append(" and (LEFT(orderNo,1) = 'M' or LEFT(orderNo,1) = 'P' or LEFT(orderNo,1) = '1'or LEFT(orderNo,1) = '2' or LEFT(orderNo,1) = '3' or LEFT(orderNo,1) = '4'  or LEFT(orderNo,1) = '5') and orderStatus='").append(ORDER_STATUS.OVER)
                    .append("' ");
            if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
                sb.append(" and a.createTime  BETWEEN  ").append(startTime).append(" and  ").append(endTime);
            } else {
                long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
                if (ValidateUtil.isAbsLong(pointTime)) {
                    sb.append(" and a.createTime > ").append(pointTime).append(" ");
                }
            }
            if (ValidateUtil.isID(agentId)) {
                sb.append(" and agentId =").append(agentId);
            }
            sb.append(" ORDER BY id DESC ");

            try {
                if (!isNoCount) {
                    StringBuffer sbCount = new StringBuffer();
                    sbCount.append("select count(1) counts ").append(sb.toString());
                    totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
                }

                if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                    StringBuffer sbSql = new StringBuffer();
                    sbSql.append("select ")
                            .append(selectFiled)
                            .append(sb.toString()).append(" LIMIT ").append((page - 1) * size).append(",").append(size);
                    list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
                }
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("查询失败，请稍后再试");
            }
        }


        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, totalCount);
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //获取自取的订单  管理员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/ziqu/list")
    @ResponseBody
    public String order_admin_ziqu_list(String token, Long agentId, Integer orderType, String cityAdminUsername, String city, String county, Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        //验证是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        String orderTypeStr = "";
        if (SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE != null && SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE == 1) {

        } else {
            if (null == orderType) {
                orderTypeStr = "";
            } else {
                if (0 == ORDER_TYPE.SERVICE_LOCK - orderType) {
                    //如果是开锁订单
                    orderTypeStr += " and orderStatus != " + ORDER_STATUS.PAYED;
                }
                orderTypeStr += " and orderType = " + orderType;
            }
        }

        List<OrderInfo> list = null;
        String cityStr = "";
        if (ValidateUtil.isNotNull(city)) {
            if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                if (JYPinyinHelper.isChinese(city)) {
                    city = JYPinyinHelper.toHanyuPinyin(city);
                } else {
                    city = city.toLowerCase();
                }
            }
            cityStr = " and shopCity='" + city + "'";
        }
        String cityUsername = "";
        String leftUserAdmin = "";
        if (ValidateUtil.isNotNull(cityAdminUsername)) {
            cityUsername = " and uar.username='" + cityAdminUsername + "' ";
//            leftUserAdmin = " left join " + PojoTables.SHOP_AGENT_RELATION + " sar on sar.agentId = ori.agentId and sar.delFlag = 0" +
//                    " left join " + PojoTables.USER_AGENT_RELATION + " uar on uar.agentId = sar.agentId and uar.delFlag = 0";
            leftUserAdmin = " left join " + PojoTables.USER_AGENT_RELATION + " uar on uar.agentId = ori.agentId and uar.delFlag = 0";
        }

//        StringBuffer sb = new StringBuffer();
//        sb.append(" from ").append(PojoTables.OrderInfo).append(" where delFlag = 0 ").append(cityStr).append(orderTypeStr).append(" and  (orderStatus='").append(ORDER_STATUS.OVER).append("' OR orderStatus='").append(ORDER_STATUS.CANCEL)
//                .append("' OR orderStatus='").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append("' OR orderStatus='").append(ORDER_STATUS.PAYED_CANCEL)
//                .append("' ) ORDER BY createTime DESC ");

        StringBuffer sb = new StringBuffer();
        sb.append(" from ").append(PojoTables.OrderInfo).append(" ori ").append(leftUserAdmin)
                .append(" where ori.delFlag = 0 and ori.isZiqu = ").append(ZI_QU_TYPE.ZHI_YOU).append(cityStr).append(cityUsername).append(orderTypeStr)
                .append(" and (LEFT(ori.orderNo,1) = 'M' or LEFT(ori.orderNo,1) = 'P' or LEFT(ori.orderNo,1) = '1' or LEFT(ori.orderNo,1) = '2' or LEFT(ori.orderNo,1) = '3' or LEFT(ori.orderNo,1) = '4'  or LEFT(ori.orderNo,1) = '5') and ori.orderStatus='").append(ORDER_STATUS.OVER)
                .append("'");
        if (ValidateUtil.isID(agentId)) {
            sb.append(" and ori.agentId =").append(agentId);
        }
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
            sb.append(" and ori.createTime between ").append(startTime).append(" and ").append(endTime);
        } else {
            long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
            if (ValidateUtil.isAbsLong(pointTime)) {
                sb.append(" and ori.createTime > ").append(pointTime).append(" ");
            }
        }
        sb.append(" ORDER BY ori.createTime DESC ");

        Long totalCount = 0l;
        try {
            if (!isNoCount) {
                StringBuffer sbCount = new StringBuffer();
                sbCount.append("select count(1) counts ").append(sb.toString());
                totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
            }

            if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select ori.* ").append(sb.toString()).append(" LIMIT ").append((page - 1) * size).append(",").append(size);
                list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, totalCount);
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //获取直邮订单  管理员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/zhiyou/list")
    @ResponseBody
    public String order_admin_ziqu_2_list(String token, Integer orderType, String cityAdminUsername, String city, String county, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        //验证是否有权限s
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        String orderTypeStr = "";
        if (SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE != null && SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE == 1) {

        } else {
            if (null == orderType) {
                orderTypeStr = "";
            } else {
                if (0 == ORDER_TYPE.SERVICE_LOCK - orderType) {
                    //如果是开锁订单
                    orderTypeStr += " and orderStatus != " + ORDER_STATUS.PAYED;
                }
                orderTypeStr += " and orderType = " + orderType;
            }
        }

        List<OrderInfo> list = null;
        String cityStr = "";
        if (ValidateUtil.isNotNull(city)) {
            if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                if (JYPinyinHelper.isChinese(city)) {
                    city = JYPinyinHelper.toHanyuPinyin(city);
                } else {
                    city = city.toLowerCase();
                }
            }
            cityStr = " and shopCity='" + city + "'";
        }
        String cityUsername = "";
        String leftUserAdmin = "";
        if (ValidateUtil.isNotNull(cityAdminUsername)) {
            cityUsername = " and uar.username='" + cityAdminUsername + "' ";
//            leftUserAdmin = " left join " + PojoTables.SHOP_AGENT_RELATION + " sar on sar.agentId = ori.agentId and sar.delFlag = 0" +
//                    " left join " + PojoTables.USER_AGENT_RELATION + " uar on uar.agentId = sar.agentId and uar.delFlag = 0";
            leftUserAdmin = " left join " + PojoTables.USER_AGENT_RELATION + " uar on uar.agentId = ori.agentId and uar.delFlag = 0";
        }

//        StringBuffer sb = new StringBuffer();
//        sb.append(" from ").append(PojoTables.OrderInfo).append(" where delFlag = 0 ").append(cityStr).append(orderTypeStr).append(" and  (orderStatus='").append(ORDER_STATUS.OVER).append("' OR orderStatus='").append(ORDER_STATUS.CANCEL)
//                .append("' OR orderStatus='").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append("' OR orderStatus='").append(ORDER_STATUS.PAYED_CANCEL)
//                .append("' ) ORDER BY createTime DESC ");

        StringBuffer sb = new StringBuffer();
        sb.append(" from ").append(PojoTables.OrderInfo).append(" ori ").append(leftUserAdmin)
                .append(" where ori.delFlag = 0 and ori.isZiqu = ").append(ZI_QU_TYPE.ZHI_YOU).append(cityStr).append(cityUsername).append(orderTypeStr)
                .append(" and (LEFT(ori.orderNo,1) = 'M' or LEFT(ori.orderNo,1) = 'P' or LEFT(ori.orderNo,1) = '1' or LEFT(ori.orderNo,1) = '2' or LEFT(ori.orderNo,1) = '3' or LEFT(ori.orderNo,1) = '4'  or LEFT(ori.orderNo,1) = '5') ")
                .append(" ORDER BY ori.createTime DESC ");

        Long totalCount = 0l;
        try {
            if (!isNoCount) {
                StringBuffer sbCount = new StringBuffer();
                sbCount.append("select count(1) counts ").append(sb.toString());
                totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
            }

            if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select ori.* ").append(sb.toString()).append(" LIMIT ").append((page - 1) * size).append(",").append(size);
                list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, totalCount);
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //获取正在退款的订单  管理员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/refunding/list")
    @ResponseBody
    public String order_admin_refunding_list(String token, Long agentId, Integer orderType, String cityAdminUsername, String city, String county,Long startTime,Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        //验证是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        String orderTypeStr = "";
        if (SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE != null && SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE == 1) {

        } else {
            if (null == orderType) {
                orderTypeStr = "";
            } else {
                if (0 == ORDER_TYPE.SERVICE_LOCK - orderType) {
                    //如果是开锁订单
                    orderTypeStr += " and orderStatus != " + ORDER_STATUS.PAYED;
                }
                orderTypeStr += " and orderType = " + orderType;
            }
        }

        List<OrderInfo> list = null;
        String cityStr = "";
        if (ValidateUtil.isNotNull(city)) {
            if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                if (JYPinyinHelper.isChinese(city)) {
                    city = JYPinyinHelper.toHanyuPinyin(city);
                } else {
                    city = city.toLowerCase();
                }
            }
            cityStr = " and shopCity='" + city + "'";
        }
        String cityUsername = "";
        String leftUserAdmin = "";
        if (ValidateUtil.isNotNull(cityAdminUsername)) {
            cityUsername = " and uar.username='" + cityAdminUsername + "' ";
//            leftUserAdmin = " left join " + PojoTables.SHOP_AGENT_RELATION + " sar on sar.agentId = ori.agentId and sar.delFlag = 0" +
//                    " left join " + PojoTables.USER_AGENT_RELATION + " uar on uar.agentId = sar.agentId and uar.delFlag = 0";
            leftUserAdmin = " left join " + PojoTables.USER_AGENT_RELATION + " uar on uar.agentId = ori.agentId and uar.delFlag = 0";
        }

//        StringBuffer sb = new StringBuffer();
//        sb.append(" from ").append(PojoTables.OrderInfo).append(" where delFlag = 0 ").append(cityStr).append(orderTypeStr).append(" and  (orderStatus='").append(ORDER_STATUS.OVER).append("' OR orderStatus='").append(ORDER_STATUS.CANCEL)
//                .append("' OR orderStatus='").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append("' OR orderStatus='").append(ORDER_STATUS.PAYED_CANCEL)
//                .append("' ) ORDER BY createTime DESC ");

        StringBuffer sb = new StringBuffer();
        sb.append(" from ").append(PojoTables.OrderInfo).append(" ori ").append(leftUserAdmin)
                .append(" where ori.delFlag = 0  ").append(cityStr).append(cityUsername).append(orderTypeStr)
                .append(" and (LEFT(ori.orderNo,1) = 'M' or LEFT(ori.orderNo,1) = 'P' or LEFT(ori.orderNo,1) = '1' or LEFT(ori.orderNo,1) = '2' or LEFT(ori.orderNo,1) = '3' or LEFT(ori.orderNo,1) = '4'  or LEFT(ori.orderNo,1) = '5') and ori.isRefundApply=1")
        ;
        if (ValidateUtil.isID(agentId)) {
            sb.append(" and ori.agentId =").append(agentId);
        }
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
            sb.append(" and ori.createTime between ").append(startTime).append(" and ").append(endTime);
        } else {
            long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
            if (ValidateUtil.isAbsLong(pointTime)) {
                sb.append(" and ori.createTime > ").append(pointTime).append(" ");
            }
        }
        sb.append(" ORDER BY ori.createTime DESC ");

        Long totalCount = 0l;
        try {
            if (!isNoCount) {
                StringBuffer sbCount = new StringBuffer();
                sbCount.append("select count(1) counts ").append(sb.toString());
                totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
            }

            if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select ori.* ").append(sb.toString()).append(" LIMIT ").append((page - 1) * size).append(",").append(size);
                list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
            }

        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, totalCount);
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //获取全部订单  管理员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/all/list")
    @ResponseBody
    public String order_admin_all_list(String token, Long agentId, Integer orderType, @RequestParam(defaultValue = "0") Integer isGroupOrder, Integer orderStatus,
                                       Long startTime, Long endTime,
                                       String city, String county, String region, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }


        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        //验证是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        List<OrderInfo> list = null;
        long totalCount = 0L;

        if (user.getUserType() == UserType.ADMIN) {
            // 城代
            StringBuffer sb = new StringBuffer();
            sb.append(" FROM ").append(PojoTables.OrderInfo).append(" a ")
                    .append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append("  b ON a.agentId = b.agentId ")
                    //   .append(" LEFT JOIN ").append(PojoTables.SHOP_AGENT_RELATION).append(" c ON b.agentId= c.agentId ")
                    .append(" WHERE a.delFlag = 0 AND b.delFlag =0 ")
                    .append(" AND  b.username = '").append(user.getUsername()).append("' ");
            //.append("' AND c.delFlag = 0  AND c.id IS NOT NULL ");

            if (ValidateUtil.isID(agentId)) {
                sb.append(" and a.agentId =").append(agentId);
            }
            if (null != orderStatus && orderStatus != 0) {
                sb.append(" and a.orderStatus = ").append(orderStatus);
            }
            if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
                sb.append(" and a.createTime between ").append(startTime).append(" and  ").append(endTime).append(" ");
            } else {
                long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
                sb.append(ValidateUtil.isAbsLong(pointTime) ? " and a.createTime > " + pointTime + " " : " ");
            }
            if (SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE != null && SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE == 1) {

            } else {
                if (null != orderType) {
                    sb.append(" AND a.orderType = ").append(orderType);
                } else {
                    if (isGroupOrder == 1) {
                        sb.append(" and a.orderType = ").append(ORDER_TYPE.GROUP_ORDER);
                    } else {
                        sb.append(" and a.orderType != ").append(ORDER_TYPE.GROUP_ORDER);
                    }
                }
            }

            sb.append(" ORDER BY a.id DESC ");
            try {
                if (!isNoCount) {
                    StringBuffer sbB = new StringBuffer();
                    sbB.append("SELECT count(a.orderno) counts ").append(sb.toString());
                    totalCount = UserDaoSql.getInstance().getCount(sbB.toString());
                }

                if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                    StringBuffer sbA = new StringBuffer();
                    sbA.append("SELECT ")
                            .append(selectFiled)
                            .append(sb.toString());
                    sbA.append(" limit ").append((page - 1) * size).append(",").append(size);
                    list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbA.toString());
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            QueryCondition query = QueryCondition.getInstance();
            Expression expression = Expression.getInstance();
            expression.addChild("delFlag", 0);//所有未删除的
//            String orderT = "";
            if (isGroupOrder == 1) {
                expression.addChild("orderType", ORDER_TYPE.GROUP_ORDER);
            } else {
                expression.addChild("orderType", Expression.OP_NE, ORDER_TYPE.GROUP_ORDER);
            }
            if (null != orderStatus && orderStatus != 0) {
                expression.addChild("orderStatus", orderStatus);//是否是团购订单
            }
            // 时间查询
            if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
                expression.addChild("createTime", ">=", startTime);
                expression.addChild("createTime", "<=", endTime);
            } else {
                long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
                if (ValidateUtil.isAbsLong(pointTime)) {
                    expression.addChild("createTime", ">=", pointTime);
                }
            }
            if (user.getUserType() == UserType.AGENT_MANAGER) {
                // 区域管理
                AgentManagerInfo info = AgentManagerMemory.getInstance().get(user.getUsername());
                if (info == null) {
                    return AjaxResult.successResult(null, 0);
                }
                List<CityAgent> cityAgents = CityAgentMemory.getInstance().listByAgentManagerUsername(user.getUsername());
                if (!ValidateUtil.isAbsList(cityAgents)) {
                    return AjaxResult.successResult(null, 0);
                }
                Set<Long> agentIdSet = cityAgents.stream().map(b -> b.getId()).collect(Collectors.toSet());
                expression.addChild("agentId", Expression.OP_IN, StringUtils.join(agentIdSet, ",")); // 商圈
            }
            if (ValidateUtil.isNotNull(city)) {
                if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                    if (JYPinyinHelper.isChinese(city)) {
                        city = JYPinyinHelper.toHanyuPinyin(city);
                    } else {
                        city = city.toLowerCase();
                    }
                }
                expression.addChild("shopCity", city);
            }
            if (ValidateUtil.isNotNull(county)) {
                expression.addChild("county", county);
            }
            if (SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE != null && SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE == 1) {

            } else {
                if (null != orderType) {
                    expression.addChild("orderType", orderType);
                }
            }

            if (ValidateUtil.isID(agentId)) {
                expression.addChild("agentId", agentId);
            }
            query.addCondition(expression);
            query.addOrders("id", "desc");
            query.setPage(page);
            query.setSize(size);
            String sql = DaoUtils.getSql(PojoTables.OrderInfo, query);
            String sqlCount = DaoUtils.getSqlCount(PojoTables.OrderInfo, query);

            try {
                if (!isNoCount) {
                    totalCount = UserDaoSql.getInstance().getCount(sqlCount);
                }

                if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                    list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sql);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                // 系统派单，自动接单
                voList = voList.stream().map(l -> postStatus(l)).collect(Collectors.toList());
                // 转接单
                Set<String> tmpSet = new HashSet<>();
                for (OrderInfoVO o : voList) {
                    tmpSet.add(o.getOrderNo());
                }
                List<HashMap<String, Object>> opList = getOrderPostman(tmpSet);
                if (null != opList) {
                    voList = voList.stream().map(v -> getPost(v, opList)).collect(Collectors.toList());
                }
                return AjaxResult.successResult(voList, totalCount);
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }

    // 获取配送状态
    public static OrderInfoVO postStatus(OrderInfoVO orderInfoVO) {
        List<OrderStatus> listOS = getOrderStatus(orderInfoVO.getOrderNo());
        if (ValidateUtil.isAbsList(listOS)) {
            for (OrderStatus orderStatus : listOS) {
                if (orderStatus.getOrderStatus() == ORDER_STATUS.POSTMAN_ZHIDING) {
                    if (orderStatus.getCreateUser().equals("sadmin")) {
                        orderInfoVO.setPostOrderStatus("自动派单");
                    } else {
                        orderInfoVO.setPostOrderStatus("骑手抢单");
                    }
                }
            }
        }
        return orderInfoVO;
    }

    private static OrderInfoVO getPost(OrderInfoVO orderInfoVO, List<HashMap<String, Object>> list) {

        for (int i = 0; i < list.size(); i++) {
            if (orderInfoVO.getOrderNo().equals(list.get(i).get("orderNo"))) {
                orderInfoVO.setPostOrderStatus("转接单");
            }
        }
        return orderInfoVO;
    }

    private static List<OrderStatus> getOrderStatus(String orderNo) {
        List<OrderStatus> list = OrderStatusMemory.getInstance().list(orderNo);
        return list;
    }

    // 获取转接单
    private static List<HashMap<String, Object>> getOrderPostman(Set<String> orderNo) {
//        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return null;
                }
//                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
//                    isNoCount = true;
//                }
//                break;
            }
        }
        String sql = "select distinct orderNo from order_postman where delFlag=0 and orderNo in('" + StringUtils.join(orderNo, "','") + "')";
        List<HashMap<String, Object>> list = null;
        try {
            list = UserDaoSql.getInstance().queryBySql(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            return list;
        }
        return null;
    }

    // 积分商城的订单 (喜燕)
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/integral/list")
    @ResponseBody
    public String order_integral_by_status(String token, Integer orderStatus, Integer page, Integer size, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        List<ShopInfo> shopInfoList = ShopMemory.getInstance().listOfIntegralShop(SHOP_IS_INTEGRAL.HAS_INTEGRAL_SHOP);
        if (!ValidateUtil.isAbsList(shopInfoList)) {
            System.out.print("没有**商城");
            return AjaxResult.successResult(0, 0, null);
        }
        ShopInfo shopInfo = null;
        if (null != SYS_SETTINGS.IS_INTEGRAL_CITY_AGENT && 0 == 1 - SYS_SETTINGS.IS_INTEGRAL_CITY_AGENT && StringUtils.isNotBlank(username)) {
            // 积分是代理模式 -> 代理有各自的商城
            for (ShopInfo info : shopInfoList) {
                if (info.getOwnName().equals(username) && info.getCreateUser().equals(username)) {
                    // 该代理的积分商城信息
                    shopInfo = info;
                }
            }
        } else {
            // 普通积分模式 积分按城市计算 只有一个总平台的积分商城
            shopInfo = shopInfoList.get(0);
        }

        if (shopInfo == null) {
            System.out.print("没有**商城");
            return AjaxResult.successResult(0, 0, null);
        }
        List<OrderInfo> orderInfoList = ShopOrderMemoryMan.listOfOrderType(shopInfo.getId(), ORDER_TYPE.INTEGRAL_ORDER, null, null);
        List<OrderInfo> list = new ArrayList<>();
        if (orderStatus != null) {
            if (ValidateUtil.isAbsList(orderInfoList)) {
                for (OrderInfo o : orderInfoList) {
                    if (o == null) {
                        continue;
                    }
                    if (orderStatus == ORDER_STATUS.POSTMAN_FINISH || orderStatus == ORDER_STATUS.OVER) {
                        if (o.getOrderStatus() - ORDER_STATUS.POSTMAN_FINISH != 0 && o.getOrderStatus() - ORDER_STATUS.OVER != 0) {
                            continue;
                        }
                    } else {
                        if (o.getOrderStatus() - orderStatus != 0) {
                            continue;
                        }
                    }
                    list.add(o);
                }
            }
        } else {
            list.addAll(orderInfoList);
        }

        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoVO) {
                    continue;
                }
                if (ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }
                voList.add(orderInfoVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                JYListSort.sortDesc(voList, "createTime");
                JYPageUtils.PageList pageList = JYPageUtils.getList(voList, page, size);
                return AjaxResult.successResult(pageList.totalCount, pageList.list.size(), pageList.list);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }


    @RequestMapping(method = RequestMethod.POST, value = "/admin/postman/xl/dispatch/change")
    @ResponseBody
    public String admin_postman_xl_dispatch_change(String token, Long fromCityLineId, Long toCityLineId, String postmanUsername) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNull(postmanUsername)) {
            return AjaxResult.errorResult("配送员账号不能为空");
        }
        if (fromCityLineId != null) {
            ConcurrentHashMap<Long, Set<String>> map = dataMap.get(user.getUsername());
            if (map != null) {
                Set<String> set = map.get(fromCityLineId);
                if (set != null && set.contains(fromCityLineId)) {
                    set.remove(fromCityLineId);
                }
            }
        }
        if (toCityLineId != null) {
            ConcurrentHashMap<Long, Set<String>> map = dataMap.get(user.getUsername());
            if (map != null) {
                Set<String> set = map.get(toCityLineId);
                if (set == null) {
                    set = new HashSet<>();
                }
                if (!set.contains(toCityLineId)) {
                    set.add(postmanUsername);
                }
            }
        }
        return AjaxResult.successResult();
    }

    //未分配配送员订单列表 管理员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/undelivery/list")
    @ResponseBody
    public String order_unDelivery_list(String token, Integer orderType, String city, String county, String region,
                                        Long shopId,
                                        Long agentId,
                                        Integer isCityAgent,  //   //是否按代理获取 0否 1是
                                        Long createTime, Integer page, Integer size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }

        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 0;
        }


        String sysCityAdminUsername = user.getUsername();
        // add by yangtk  2019年5月30日18:16:38
        if (user.getUserType() == UserType.AGENT_MANAGER) {
            AgentManagerInfo info = AgentManagerMemory.getInstance().get(user.getUsername());
            if (info == null) {
                return AjaxResult.successResult(null, 0);
            }
            List<CityAgent> cityAgents = CityAgentMemory.getInstance().listByAgentManagerUsername(user.getUsername());
            if (!ValidateUtil.isAbsList(cityAgents)) {
                return AjaxResult.successResult(null, 0);
            }
            List<OrderInfo> orderInfoList = null;
            if (agentId != null) {
                boolean b = CityAgentMemory.getInstance().cityAgentInAgentManger(user.getUsername(), agentId);
                if (!b) {
                    return AjaxResult.successResult(null, 0);
                } else {
                    List<Long> set = new ArrayList<>();
                    set.add(agentId);
                    Set<Long> shopIdSet = null;
                    if (ValidateUtil.isID(shopId)) {
                        shopIdSet = new HashSet<>();
                        shopIdSet.add(shopId);
                    }
//                    orderInfoList = AgentOrderMemoryMan.agentUnDeliveryList(set, createTime, isLoadMore, orderType, POSTMAN_TYPE.POSTMAN, null, shopId, false);
                    orderInfoList = AgentOrderMemoryMan.agentUnDeliveryList(set, createTime, isLoadMore, orderType, POSTMAN_TYPE.POSTMAN, null, shopIdSet, false);
                }
            } else {
                Set<Long> shopIdSet = null;
                if (ValidateUtil.isID(shopId)) {
                    shopIdSet = new HashSet<>();
                    shopIdSet.add(shopId);
                }
                List<Long> list = cityAgents.stream().map(nb -> nb.getId()).collect(Collectors.toList());
                if (ValidateUtil.isAbsList(list)) {
//                    orderInfoList = AgentOrderMemoryMan.agentUnDeliveryList(list, createTime, isLoadMore, orderType, POSTMAN_TYPE.POSTMAN, null, shopId, false);
                    orderInfoList = AgentOrderMemoryMan.agentUnDeliveryList(list, createTime, isLoadMore, orderType, POSTMAN_TYPE.POSTMAN, null, shopIdSet, false);
                }
            }
            if (ValidateUtil.isAbsList(orderInfoList)) {
                // 分页判断
                long totalCount = 0;
                List<OrderInfo> newList = null;
                if (ValidateUtil.isNotAbsInteger(page)) {
//                    newList = orderInfoList.subList(0, size - 1);
                    if (orderInfoList.size() > size) {
                        newList = orderInfoList.subList(0, size - 1);
                    } else {
                        newList = orderInfoList;
                    }
                } else {
                    // 分页
                    JYPageUtils.PageList pageList = JYPageUtils.getList(orderInfoList, page, size);
                    newList = (List<OrderInfo>) pageList.list;
                    totalCount = pageList.totalCount;
                }
                List<OrderInfoAdminVO> orderInfoAdminVOList = new ArrayList<OrderInfoAdminVO>();
                for (OrderInfo orderInfo : newList) {
                    OrderInfoAdminVO orderInfoAdminVO = new OrderInfoAdminVO();

                    try {
                        ObjectUtils.copyPropertiesExclude(orderInfo, orderInfoAdminVO, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    if (null == orderInfoAdminVO) {
                        continue;
                    }

                    //获取配送员抢单信息
                    List<OrderGrabInfo> grabInfoList = PostmanGrabMemory.getInstance().grabListOfOrder(orderInfoAdminVO.getOrderNo());
                    if (ValidateUtil.isAbsList(grabInfoList)) {
                        orderInfoAdminVO.setGrabInfo(grabInfoList);
                    }

                    if (ValidateUtil.isNotNull(orderInfoAdminVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoAdminVO.getShopImageUrl())) {
                        orderInfoAdminVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoAdminVO.getShopImageUrl());
                    }
                    if (ValidateUtil.isNotNull(orderInfoAdminVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoAdminVO.getPostmanImageUrl())) {
                        orderInfoAdminVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoAdminVO.getPostmanImageUrl());
                    }
                    orderInfoAdminVOList.add(orderInfoAdminVO);
                }
                return AjaxResult.successResult(orderInfoAdminVOList, totalCount);

            } else {
                return AjaxResult.successResult(null, 0);
            }
        }
        // 多级代理管理模式
        // end

        // 按代理获取
        List<Long> shopIdList = null;
        if (null != isCityAgent && isCityAgent - 1 == 0) {
//            shopIdList = OrderListMan.getShopIdList(user.getUsername());
            shopIdList = OrderListMan.getShopIdList(sysCityAdminUsername);
        }

        if (SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE != null && SYS_SETTINGS.CUSTOMIZE_ORDER_TYPE == 1) {
            // 若是自定义类型 则不进行订单类型判断
            orderType = null;
        }
        List<OrderInfo> list = AdminOrderMemoryMan.cityUnDeliveryList(city, county, region, createTime, isLoadMore, orderType, null, null, false);
        List<OrderInfoAdminVO> orderInfoAdminVOList = new ArrayList<OrderInfoAdminVO>();
        if (ValidateUtil.isAbsList(list)) {
            // 分页判断
            long totalCount = 0;
            List<OrderInfo> newList = null;
            if (ValidateUtil.isNotAbsInteger(page)) {
//                newList = list.subList(0, size - 1);
                if (list.size() > size) {
                    newList = list.subList(0, size - 1);
                } else {
                    newList = list;
                }
            } else {
                // 分页
                JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
                newList = (List<OrderInfo>) pageList.list;
                totalCount = pageList.totalCount;
            }
            for (int i = 0; i < newList.size(); i++) {
                if (null == newList.get(i)) {
                    continue;
                }

                // for 为抢单的订单列表
                //      for 城市代理下的所有店铺
                //          if 店铺id == 订单店铺id
                //            break;
                //          else

                // 按代理筛选
                Boolean isCityAgentV = false;
                if (null != isCityAgent && isCityAgent - 1 == 0) {
                    if (ValidateUtil.isAbsList(shopIdList)) {
                        for (int y = 0; y < shopIdList.size(); y++) {
                            if (null == shopIdList.get(y)) {
                                continue;
                            }
                            // 根据Id获取该店铺信息
                            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopIdList.get(y));
                            // 如果该店铺与该订单的店铺相同，则不循环
                            if (null != shopInfo && shopInfo.getId() - newList.get(i).getShopId() == 0) {
                                isCityAgentV = true;
                                break;
                            }
                        }
                    }
                    if (!isCityAgentV) {
                        continue;
                    }
                }

                if (ValidateUtil.isID(shopId) && shopId - newList.get(i).getShopId() != 0) {
                    continue;
                }




                OrderInfoAdminVO orderInfoAdminVO = new OrderInfoAdminVO();

                try {
                    ObjectUtils.copyPropertiesExclude(newList.get(i), orderInfoAdminVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoAdminVO) {
                    continue;
                }


                //获取配送员抢单信息
                List<OrderGrabInfo> grabInfoList = PostmanGrabMemory.getInstance().grabListOfOrder(orderInfoAdminVO.getOrderNo());
                if (ValidateUtil.isAbsList(grabInfoList)) {
                    orderInfoAdminVO.setGrabInfo(grabInfoList);
                }

                if (ValidateUtil.isNotNull(orderInfoAdminVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoAdminVO.getShopImageUrl())) {
//                    orderInfoAdminVO.setShopImageUrl(Common.imageUrl + orderInfoAdminVO.getShopImageUrl());
                    orderInfoAdminVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoAdminVO.getShopImageUrl());
                }
                if (ValidateUtil.isNotNull(orderInfoAdminVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoAdminVO.getPostmanImageUrl())) {
//                    orderInfoAdminVO.setPostmanImageUrl(Common.imageUrl + orderInfoAdminVO.getPostmanImageUrl());
                    orderInfoAdminVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoAdminVO.getPostmanImageUrl());
                }
                orderInfoAdminVOList.add(orderInfoAdminVO);
            }


            return AjaxResult.successResult(orderInfoAdminVOList, totalCount);
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //已抢订单列表
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/grab/list")
    @ResponseBody
    public String order_grab_list(String token, Integer orderType, String city, String county, String region, Long createTime, int size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }

        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 0;
        }

        List<OrderInfo> list = AdminOrderMemoryMan.grabList(city, county, region, createTime, size, isLoadMore, orderType);
        List<OrderInfoAdminVO> orderInfoAdminVOList = new ArrayList<OrderInfoAdminVO>();
        if (ValidateUtil.isAbsList(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }

                OrderInfoAdminVO orderInfoAdminVO = new OrderInfoAdminVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoAdminVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoAdminVO) {
                    continue;
                }

                //获取配送员抢单信息
                List<OrderGrabInfo> grabInfoList = PostmanGrabMemory.getInstance().grabListOfOrder(orderInfoAdminVO.getOrderNo());
                if (ValidateUtil.isAbsList(grabInfoList)) {
                    orderInfoAdminVO.setGrabInfo(grabInfoList);
                }

                if (ValidateUtil.isNotNull(orderInfoAdminVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoAdminVO.getShopImageUrl())) {
//                    orderInfoAdminVO.setShopImageUrl(Common.imageUrl + orderInfoAdminVO.getShopImageUrl());
                    orderInfoAdminVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoAdminVO.getShopImageUrl());
                }
                if (ValidateUtil.isNotNull(orderInfoAdminVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoAdminVO.getPostmanImageUrl())) {
//                    orderInfoAdminVO.setPostmanImageUrl(Common.imageUrl + orderInfoAdminVO.getPostmanImageUrl());
                    orderInfoAdminVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoAdminVO.getPostmanImageUrl());
                }
                orderInfoAdminVOList.add(orderInfoAdminVO);
            }


            return AjaxResult.successResult(orderInfoAdminVOList.size(), orderInfoAdminVOList);
        }

        return AjaxResult.successResult(0, null);
    }

    //订单查询
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/search/list")
    @ResponseBody
    public String order_admin_list(String token,
                                   String city, String county, Integer orderType,
                                   Integer isSquareOrder,   //  是否是创业商圈订单
                                   String shopUsername, String shopName,
                                   Long agentId,
                                   String postmanUsername,
                                   String name, String phone, String address, //购买人信息
                                   String orderNo, //订单编号
                                   Integer orderStatus,//订单状态
                                   Integer orderOverTime,//超时订单
                                   Integer orderBadOverTime,//严重超时订单
                                   @RequestParam(defaultValue = "0") Integer isGroupOrder, // 是否是团购订单
                                   @RequestParam(defaultValue = "-1") Integer isZiQu, // 取货方式(-1全部 0配送 1自取 2到店堂食 3精选直邮)
                                   Long shopId,//店铺ID
                                   Long cityLineId,//城市线路id
                                   Long startTime, Long endTime,
                                   Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
//        验证用户是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        if (orderType == null) {
            orderType = 0;
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }

        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        List<OrderInfo> list = new ArrayList<>();
        Set<Long> agentIdSet = null;
        if (user.getUserType() == UserType.AGENT_MANAGER) {
            // 区域代理的话
            AgentManagerInfo info = AgentManagerMemory.getInstance().get(user.getUsername());
            if (info == null) {
                return AjaxResult.successResult(null, 0);
            }
            List<CityAgent> cityAgents = CityAgentMemory.getInstance().listByAgentManagerUsername(user.getUsername());
            if (!ValidateUtil.isAbsList(cityAgents)) {
                return AjaxResult.successResult(null, 0);
            }
            agentIdSet = cityAgents.stream().map(b -> b.getId()).collect(Collectors.toSet());
        }

        String t_order_info = PojoTables.OrderInfo;
//        String t_order_pay = PojoTables.OrderPay;
        if (null != SYS_SETTINGS.USE_BAK_ORDER && 0 == 1 - SYS_SETTINGS.USE_BAK_ORDER) {
            boolean userBakDB = false;
            if (null != orderStatus && (0 == orderStatus - ORDER_STATUS.OVER
                    || 0 == orderStatus - ORDER_STATUS.CANCEL
                    || 0 == orderStatus - ORDER_STATUS.CANCEL_BY_SYSTEM
                    || 0 == orderStatus - ORDER_STATUS.PAYED_CANCEL
            )) {
                userBakDB = true;
            }
            if ((null != orderOverTime && orderOverTime == 1) || (null != orderBadOverTime && orderBadOverTime == 1)) {
                userBakDB = true;
            }
            if (userBakDB) {
                String dataDbName = OrderBakTaskUtils.getDataDbName();
                if (ValidateUtil.isNotNull(dataDbName)) {
                    t_order_info = dataDbName + "." + PojoTables.D_ORDER_INFO;
//                    t_order_pay = dataDbName + "." + PojoTables.D_ORDER_PAY;
                }
            }
        }

        //不按店铺查
        StringBuffer sb = new StringBuffer();
        //数据库中查出订单编号  再去缓存取内容
        if (ValidateUtil.isNotNull(shopUsername) || ValidateUtil.isNotNull(shopName)) {
            sb.append(" from ").append(t_order_info).append(" a ")
                    .append(" left join ").append(PojoTables.ShopInfo).append(" b on a.shopId = b.id ");
            if (user.getUserType() == UserType.ADMIN) {
                // 城代
                sb.append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append("  d ON a.agentId = d.agentId ");
//                        sb.append(" LEFT JOIN ").append(PojoTables.SHOP_AGENT_RELATION).append(" e ON d.agentId= e.agentId ");
            }
            sb.append(" where b.id is not null and b.delFlag = 0 and a.delFlag = 0 and a.shopId > 0 ");
            if (user.getUserType() == UserType.AGENT_MANAGER) {
                sb.append(" and a.agentId in (").append(StringUtils.join(agentIdSet, ",")).append(") ");
            } else if (user.getUserType() == UserType.ADMIN) {
                // 城代
                sb.append(" and d.delFlag = 0 and d.username = '").append(user.getUsername()).append("' ");
//                sb.append(" and e.delFlag =0  ");
            }

            if (ValidateUtil.isNotNull(shopUsername)) {
                sb.append(" and b.shopName like '%").append(shopUsername).append("%' ");
            }
            if (ValidateUtil.isNotNull(shopName)) {
                sb.append(" and b.shopName like '%").append(shopName).append("%' ");
            }
            if (ValidateUtil.isNotNull(postmanUsername)) {
                sb.append(" and a.postmanUsername like '%").append(postmanUsername).append("%' ");
            }
            if (ValidateUtil.isNotNull(name)) {
                sb.append(" and a.buyer like '%").append(name).append("%' ");
            }
            if (isSquareOrder != null && isSquareOrder == 1) {
                sb.append(" and a.orderNo like 'P%'");
            }
            if (ValidateUtil.isNotNull(phone)) {
                sb.append(" and (a.telephone like '%").append(phone).append("%' or a.username like '%").append(phone).append("%')");
            }
            if (ValidateUtil.isNotNull(address)) {
                sb.append(" and ( a.address like '%").append(address).append("%' ");
                sb.append(" or a.address2 like '%").append(address).append("%' )");
            }
            if (ValidateUtil.isNotNull(orderNo)) {
                sb.append(" and a.orderNo like '%").append(orderNo).append("%' ");
            }
            if (isGroupOrder == 1) {
                sb.append(" and a.orderType =").append(ORDER_TYPE.GROUP_ORDER);
            } else if (isGroupOrder == 0) {
                sb.append(" and a.orderType !=").append(ORDER_TYPE.GROUP_ORDER);
            }

            if (null != orderStatus && orderStatus > 0) {
                sb.append(" and a.orderStatus = ").append(orderStatus);
            }
            if (null != orderOverTime && orderOverTime == 1) {
                sb.append(" and a.orderStatus=").append(ORDER_STATUS.OVER).append(" and ((a.ziQuTime > 0 and a.postmanFinishTime-a.ziQuTime>0) or (a.ziQuTime =0 and a.postmanFinishTime-a.createTime > a.agentPostmanOverTime*60*1000)) ");
            }
            if (null != orderBadOverTime && orderBadOverTime == 1) {
                sb.append(" and a.orderStatus=").append(ORDER_STATUS.OVER).append(" and ((a.ziQuTime > 0 and a.postmanFinishTime-a.ziQuTime>30 * 60 * 1000)")
                        .append(" or (a.ziQuTime=0 and a.postmanFinishTime-a.createTime > (a.agentPostmanOverTime+30)*60*1000))");
            }
            if (null != orderStatus && orderStatus > 0) {
                sb.append(" and a.orderStatus = ").append(orderStatus);
            }

            if (null != orderType && orderType > 0) {
                sb.append(" and a.orderType = ").append(orderType);
            }

            if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
                sb.append(" and a.createTime Between ").append(startTime).append(" and ").append(endTime);
            } else {
                long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
                if (ValidateUtil.isAbsLong(pointTime)) {
                    sb.append(" and a.createTime > ").append(pointTime).append(" ");
                }
            }
            if (null != isZiQu && isZiQu != -1) {
                sb.append(" and a.isZiQu = ").append(isZiQu).append(" ");
            }

            if (ValidateUtil.isNotNull(city)) {
                if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                    if (JYPinyinHelper.isChinese(city)) {
                        city = JYPinyinHelper.toHanyuPinyin(city);
                    } else {
                        city = city.toLowerCase();
                    }
                }
//                sb.append(" and cag.city = '").append(city).append("'");
                sb.append(" and (a.city like '%").append(city).append("%'").append(" or a.shopCity like '%").append(city).append("%'").append(")");
            }
            if (ValidateUtil.isNotNull(county)) {
                if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                    if (JYPinyinHelper.isChinese(county)) {
                        county = JYPinyinHelper.toHanyuPinyin(county);
                    } else {
                        county = county.toLowerCase();
                    }
                }
                sb.append(" and b.county = '").append(county).append("'");
            }

        } else {
            String lefts = "";
            String isBid = "";
            if (orderType == ORDER_TYPE.SHOP_GOODS) {
                lefts = " left join " + PojoTables.ShopInfo + " b on a.shopId = b.id";
                isBid = " and b.id is not null and b.delFlag = 0 and a.shopId > 0 ";
            }

            sb.append(" from ").append(t_order_info).append(" a ").append(lefts);
            if (user.getUserType() == UserType.ADMIN) {
                // 城代
                sb.append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append("  d ON a.agentId = d.agentId ");
                //sb.append(" LEFT JOIN ").append(PojoTables.SHOP_AGENT_RELATION).append(" e ON d.agentId= e.agentId ");
            }
            sb.append(" where a.delFlag = 0 ").append(isBid);
            if (ValidateUtil.isID(cityLineId)) {
                sb.append(" and a.cityLineId =").append(cityLineId).append(" ");
            }
            if (user.getUserType() == UserType.AGENT_MANAGER) {
                sb.append(" and a.agentId in (").append(StringUtils.join(agentIdSet, ",")).append(") ");
            } else if (user.getUserType() == UserType.ADMIN) {
                // 城代
                sb.append(" and d.delFlag = 0 and d.username = '").append(user.getUsername()).append("' ");
//                sb.append(" and e.delFlag =0 ");
            }
            if (ValidateUtil.isNotNull(name)) {
                sb.append(" and a.buyer like '%").append(name).append("%' ");
            }
            if (isSquareOrder != null && isSquareOrder == 1) {
                sb.append(" and a.orderNo like 'P%'");
            }
            if (ValidateUtil.isNotNull(phone)) {
                sb.append(" and (a.telephone like '%").append(phone).append("%' or a.username like '%").append(phone).append("%') ");
            }
            if (ValidateUtil.isNotNull(postmanUsername)) {
                sb.append(" and a.postmanUsername like '%").append(postmanUsername).append("%' ");
            }
            if (ValidateUtil.isNotNull(address)) {
                sb.append(" and ( a.address like '%").append(address).append("%' ");
                sb.append(" or a.address2 like '%").append(address).append("%' ) ");
            }
            if (ValidateUtil.isNotNull(orderNo)) {
                sb.append(" and a.orderNo like '%").append(orderNo).append("%' ");
            }
//            sb.append(") ");
            if (null != orderStatus && orderStatus > 0) {
                sb.append(" and a.orderStatus = ").append(orderStatus);
            }
//            if (null != isGroupOrder && isGroupOrder == 1) {
//                sb.append(" and a.isGroupOrder=1 ");
//            }
            if (isGroupOrder == 1) {
                sb.append(" and a.orderType =").append(ORDER_TYPE.GROUP_ORDER);
            } else if (isGroupOrder == 0) {
                sb.append(" and a.orderType !=").append(ORDER_TYPE.GROUP_ORDER);
            }
            if (null != orderStatus && orderStatus > 0) {
                sb.append(" and a.orderStatus = ").append(orderStatus);
            }
            if (null != orderType && orderType > 0) {
                sb.append(" and a.orderType = ").append(orderType);
            }
            if (null != orderOverTime && orderOverTime == 1) {
                sb.append(" and a.orderStatus=").append(ORDER_STATUS.OVER).append(" and ((a.ziQuTime > 0 and a.postmanFinishTime-a.ziQuTime>0) or (a.ziQuTime =0 and a.postmanFinishTime-a.createTime > a.agentPostmanOverTime*60*1000)) ");
            }
            if (null != orderBadOverTime && orderBadOverTime == 1) {
                sb.append(" and a.orderStatus=").append(ORDER_STATUS.OVER).append(" and ((a.ziQuTime > 0 and a.postmanFinishTime-a.ziQuTime>30 * 60 * 1000)")
                        .append(" or (a.ziQuTime=0 and a.postmanFinishTime-a.createTime > (a.agentPostmanOverTime+30)*60*1000))");
            }
            if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
                sb.append(" and a.createTime Between ").append(startTime).append(" and ").append(endTime);
            } else {
                long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
                if (ValidateUtil.isAbsLong(pointTime)) {
                    sb.append(" and a.createTime > ").append(pointTime).append(" ");
                }
            }
            if (ValidateUtil.isNotNull(city)) {
                if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                    if (JYPinyinHelper.isChinese(city)) {
                        city = JYPinyinHelper.toHanyuPinyin(city);
                    } else {
                        city = city.toLowerCase();
                    }
                }
//                sb.append(" and a.city = '").append(city).append("'");
                sb.append(" and (a.city like '%").append(city).append("%'").append(" or a.shopCity like '%").append(city).append("%'").append(")");
            }
            if (ValidateUtil.isNotNull(county)) {
                if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                    if (JYPinyinHelper.isChinese(county)) {
                        county = JYPinyinHelper.toHanyuPinyin(county);
                    } else {
                        county = county.toLowerCase();
                    }
                }
                if (orderType == 1) {
                    sb.append(" and b.county = '").append(county).append("'");
                } else {
                    sb.append(" and a.county = '").append(county).append("'");
                }

            }
            if (ValidateUtil.isAbsLong(shopId)) {
                sb.append(" and a.shopId= '").append(shopId).append("'");
            }
            if (null != isZiQu && isZiQu != -1) {
                sb.append(" and a.isZiQu = ").append(isZiQu).append(" ");
            }
        }
        if (ValidateUtil.isID(agentId)) {
            sb.append(" and a.agentId =").append(agentId);
        }
        Long totalCount = 0l;
        if (!isNoCount) {
            try {
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select count(a.orderNo) as counts ");
                sbSql.append(sb.toString());
                totalCount = UserDaoSql.getInstance().getCount(sbSql.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                totalCount = 0l;
            }
        }


        List<HashMap<String, Object>> listMap = null;
        if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
            try {
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select  a.orderNo , a.createTime ");
                sb.append(" ORDER BY a.createTime DESC ");
                sbSql.append(sb.toString());
                sbSql.append(" limit ").append((page - 1) * size).append(",").append(size);
                listMap = UserDaoSql.getInstance().queryBySql(sbSql.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                listMap = null;
            }
        }

        if (ValidateUtil.isAbsList(listMap)) {
            for (int i = 0; i < listMap.size(); i++) {
                if (null == listMap.get(i)) {
                    continue;
                }
                String no = (String) listMap.get(i).get("orderNo");
                if (ValidateUtil.isNull(no)) {
                    continue;
                }
                OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(no);
                if (null == orderInfo) {
                    continue;
                }
                list.add(orderInfo);
            }
        }

        if (ValidateUtil.isAbsList(list)) {
//            list = list.stream().filter(bean->isGroupOrder == bean.getIsGroupOrder()).collect(Collectors.toList());
            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = new OrderInfoVO();
                BeanUtils.copyProperties(list.get(i), orderInfoVO);
                // try {
                //     ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                // } catch (Exception e) {
                //     e.printStackTrace();
                //     continue;
                // }
                // if (null == orderInfoVO) {
                //     continue;
                // }
                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }
                voList.add(orderInfoVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                // 系统派单，自动接单
                voList = voList.stream().map(l -> postStatus(l)).collect(Collectors.toList());
                // 转接单
                Set<String> tmpSet = new HashSet<>();
                for (OrderInfoVO o : voList) {
                    tmpSet.add(o.getOrderNo());
                }
                List<HashMap<String, Object>> opList = getOrderPostman(tmpSet);
                if (null != opList) {
                    voList = voList.stream().map(v -> getPost(v, opList)).collect(Collectors.toList());
                }
                return AjaxResult.successResult(voList, totalCount);
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    //获取退回订单列表
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/cant/finish/list")
    @ResponseBody
    public String order_cant_finish_list(String token, Integer orderType, String city, String county, String region, Long createTime, Integer size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (null == size) {
            size = 20;
        }

        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 0;
        }

        List<OrderInfo> list = AdminOrderMemoryMan.postmanCantFinishList(city, county, region, createTime, size, isLoadMore, orderType);
        List<OrderInfoAdminVO> orderInfoAdminVOList = new ArrayList<OrderInfoAdminVO>();
        if (ValidateUtil.isAbsList(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }

                OrderInfoAdminVO orderInfoAdminVO = new OrderInfoAdminVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoAdminVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoAdminVO) {
                    continue;
                }

                if (ValidateUtil.isNotNull(orderInfoAdminVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoAdminVO.getShopImageUrl())) {
//                    orderInfoAdminVO.setShopImageUrl(Common.imageUrl + orderInfoAdminVO.getShopImageUrl());
                    orderInfoAdminVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoAdminVO.getShopImageUrl());
                }
                if (ValidateUtil.isNotNull(orderInfoAdminVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoAdminVO.getPostmanImageUrl())) {
//                    orderInfoAdminVO.setPostmanImageUrl(Common.imageUrl + orderInfoAdminVO.getPostmanImageUrl());
                    orderInfoAdminVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoAdminVO.getPostmanImageUrl());
                }
                orderInfoAdminVOList.add(orderInfoAdminVO);
            }

            return AjaxResult.successResult(orderInfoAdminVOList.size(), orderInfoAdminVOList);
        }

        return AjaxResult.successResult(0, null);
    }

    // 骑手是否在指定集合中
    public static boolean postmanIsInHashSetPostman(String postman, HashSet<String> set) {
        if (ValidateUtil.isNull(postman) || set == null || set.size() == 0) {
            return false;
        }
        for (String pU : set) {
            if (pU.contains(postman)) {
                return true;
            }
        }
        return false;
    }


    //配送异常订单列表 代理登入是 只会看到自己代理下商圈去手的trouble订单
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/postman/trouble/list")
    @ResponseBody
    public String order_trouble_list(String token,
                                     String orderNo, Integer orderType,
                                     String postmanUsername,
                                     String province, String city, String county,
                                     Long startTime, Long endTime,
                                     Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

//        if (ValidateUtil.isNull(city)) {
//            return AjaxResult.errorResult("城市不能为空");
//        }

        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有查询权限");
        }

        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }

        QueryCondition query = QueryCondition.getInstance();

        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);//所有未删除的
        if (ValidateUtil.isNotNull(city)) {
            expression.addChild("city", city);
        }
        if (ValidateUtil.isNotNull(postmanUsername)) {
            expression.addChild("username", Expression.OP_LIKE, postmanUsername);
        }
//        if (ValidateUtil.isNotNull(postmanUsername)) {
//            expression.addChild("username", Expression.OP_LIKE, postmanUsername);
//        }
        if (ValidateUtil.isNotNull(orderNo)) {
            expression.addChild("orderNo", orderNo);
        }
        if (ValidateUtil.isAbsLong(startTime) && startTime > 0) {
            expression.addChild("createTime", ">=", startTime);
        }
        if (ValidateUtil.isAbsLong(endTime) && endTime > 0) {
            expression.addChild("createTime", "<=", endTime);
        }
        if (null != orderType) {
            expression.addChild("orderType", orderType);
        }
        query.addCondition(expression);
//        query.setPage(page);
        query.setSize(size);
        query.addOrders("createTime", "desc");
        query.addOrders("orderNo", "desc");
        String sql = DaoUtils.getSql(PojoTables.ORDER_POSTMAN_TROUBLE, query);
        List<OrderPostmanTrouble> list = null;
        int count = 0;
        try {
            if (!isNoCount) {
                query.setPage(1);
                count = UserDaoSql.getInstance().getCount(PojoTables.ORDER_POSTMAN_TROUBLE, query);
            }

            if (ValidateUtil.isAbsInteger(count) || isNoCount) {
                query.setPage(page);
                list = (List<OrderPostmanTrouble>) UserDaoSql.getInstance().list(OrderPostmanTrouble.class, sql);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (ValidateUtil.isAbsList(list)) {
            List<OrderPostmanTroubleVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }

                OrderPostmanTroubleVO vo = new OrderPostmanTroubleVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

                if (ValidateUtil.isNotNull(vo.getUsername())) {
                    UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(vo.getUsername());
                    if (null == userInfo) {
                        continue;
                    }
                    vo.setName(userInfo.getName());
                    vo.setSignPhoto(userInfo.getSignPhoto());
                }

                // 查询订单信息
                OrderInfoVO infoVO = new OrderInfoVO();
                // 聚合订单 ？
                if (OrderMan.isMultipleParentOrder(vo.getOrderNo())) {
                    //订单信息
                    infoVO = OrderMan.getMultipleParentOrderDetail(vo.getOrderNo(), user);
                } else {
                    // 非聚合订单
                    infoVO = getOrderDetail(vo.getOrderNo());
                }
                if (infoVO != null) {
                    vo.setInfoVO(infoVO);
                    vo.setShopName(infoVO.getShopName());
                }
                voList.add(vo);
            }
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, count);
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    // 异常订单标记为已经处理了
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/postman/trouble/deal")
    @ResponseBody
    public String order_trouble_deal(String token, Long id, String dealExplain) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        StringBuilder sql = new StringBuilder();
        sql.append(" select * from ").append(PojoTables.ORDER_POSTMAN_TROUBLE)
                .append(" where id = ").append(id).append(" and  delFlag = 0");
        OrderPostmanTrouble postmanTrouble = null;
        try {
            postmanTrouble = (OrderPostmanTrouble) UserDaoSql.getInstance().getObject(OrderPostmanTrouble.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (postmanTrouble == null || postmanTrouble.getStatus() != 0) {
            return AjaxResult.errorResult("当前状态下不可操作");
        }
        StringBuilder updateSql = new StringBuilder();
        updateSql.append(" update ").append(PojoTables.ORDER_POSTMAN_TROUBLE)
                .append(" set status =1 , dealExplain = '").append(ValidateUtil.isNull(dealExplain) ? "" : dealExplain).append("' ")
                .append(" where delFlag = 0 and id = ").append(postmanTrouble.getId());
        try {
            UserDaoSql.getInstance().executeBySql(updateSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.successResult();
    }

    //配送异常订单列表v2(搜点)
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/postman/trouble/list/v2")
    @ResponseBody
    public String order_trouble_list02(String token,
                                       String orderNo,
                                       String postmanUsername,
                                       Long startTime, Long endTime,
                                       Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }


        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }

        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }

        StringBuffer sb = new StringBuffer();
        StringBuffer sbCount = new StringBuffer();
        // 订单
        List<OrderPostmanTrouble> list = new ArrayList<>();
        // 数量
//        List<OrderPostmanTrouble> lists = new ArrayList<>();
        String cityAdminUsername = user.getUsername();
        if (UserType.COMPANY == user.getUserType() && SysCityCompanyMan.isAdminCompanyUser(cityAdminUsername)) {
            cityAdminUsername = SysCityCompanyMan.getSysCompanyOwnUsername(cityAdminUsername);
        }

        sb.append(" from ").append(PojoTables.ORDER_POSTMAN_TROUBLE).append(" a left join ").append(PojoTables.OrderInfo)
                .append(" b on b.orderNo=a.orderNo left join ").append(PojoTables.USER_AGENT_RELATION)
                .append(" c on c.agentId=b.agentId where c.username = '").append(cityAdminUsername).append("' ")
                .append(" and a.delFlag = 0 ");

        sbCount.append(sb);

        if (ValidateUtil.isNotNull(postmanUsername)) {
            sb.append(" and a.username= '").append(postmanUsername).append("' ");
        }
        if (ValidateUtil.isNotNull(orderNo)) {
            sb.append(" and a.orderNo= ").append(orderNo);
        }
        if (ValidateUtil.isAbsLong(startTime) && startTime > 0 && ValidateUtil.isAbsLong(endTime) && endTime > 0 && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" order by a.createTime desc limit ").append((page - 1) * size).append(",").append(size);

        Long totalCount = 0l;
        try {
//            list = (List<OrderPostmanTrouble>) UserDaoSql.getInstance().list(OrderPostmanTrouble.class, "select a.* " + sb.toString());
//            lists = (List<OrderPostmanTrouble>) UserDaoSql.getInstance().list(OrderPostmanTrouble.class, "select count(a.id) counts" + sbCount.toString());
            if (!isNoCount) {
                totalCount = UserDaoSql.getInstance().getCount("select count(a.id) counts" + sbCount.toString());
            }

            if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                list = (List<OrderPostmanTrouble>) UserDaoSql.getInstance().list(OrderPostmanTrouble.class, "select a.* " + sb.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            for (OrderPostmanTrouble orderPostmanTrouble : list) {
                if (orderPostmanTrouble.getUsername() == null) {
                    continue;
                }
                UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(orderPostmanTrouble.getUsername());
                if (userInfo != null && ValidateUtil.isNotNull(userInfo.getName())) {
                    orderPostmanTrouble.setName(userInfo.getName());
                }
                // 查询订单信息
                OrderInfoVO infoVO = new OrderInfoVO();
                // 聚合订单 ？
                if (OrderMan.isMultipleParentOrder(orderPostmanTrouble.getOrderNo())) {
                    //订单信息
                    infoVO = OrderMan.getMultipleParentOrderDetail(orderPostmanTrouble.getOrderNo(), user);
                }
                // 非聚合订单
                infoVO = getOrderDetail(orderPostmanTrouble.getOrderNo());
                orderPostmanTrouble.setShopName(infoVO.getShopName());
                orderPostmanTrouble.setInfoVO(infoVO);
            }
        }

        if (ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(list, totalCount);
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //-----------------------获取订单缓存当前版本
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/mem/version")
    @ResponseBody
    public String order_mem_version(String token) {
        //验证用户有效性
//        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
//        if (user == null) {
//            return AjaxResult.errorLogoutResult();
//        }
//

        // 获取当前订单缓存版本
        String orderMemVersion = OrderInfoMemory.getInstance().getOrderMemVersion();
        if (!configProperties.isProdEvn()) {
            orderMemVersion = ToolUtils.getNeedString(4);
        }

        return AjaxResult.successResult(orderMemVersion);
    }

    //-----------------------获取订单缓存当前版本
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/mem-paid/version")
    @ResponseBody
    public String order_mem_paid_version(String token) {
        // 获取当前订单缓存版本
        String orderMemPaidVersion = OrderInfoMemory.getInstance().getOrderMemPaidVersion();
        return AjaxResult.successResult(orderMemPaidVersion);
    }

    //-----------------------------老克回访订单
    //获取待回访订单列表   已支付成功的
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/visit/list")
    @ResponseBody
    public String order_visit_list(String token, Integer orderType, String city, String county, String region, Long createTime, Integer size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (null == createTime) {
            createTime = 0l;
        }
        if (null == size) {
            size = 20;
        }
        if (null == isLoadMore) {
            isLoadMore = 0;
        }


        //获取该城市订单
        List<OrderInfo> orderList = AdminOrderMemoryMan.listOfShopNotSure(city, county, region, orderType, 0, "");
        if (ValidateUtil.isAbsList(orderList)) {
            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < orderList.size(); i++) {
                OrderInfo orderInfo = orderList.get(i);
                if (null == orderInfo) {
                    continue;
                }
                if (null != orderInfo.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfo.getOrderType()) {

                } else {
                    continue;
                }
                OrderInfoVO orderInfoVO = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(orderInfo, orderInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoVO) {
                    continue;
                }
                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }
                voList.add(orderInfoVO);
            }

            List<OrderInfoVO> reList = getList(voList, createTime, size, isLoadMore);
            if (ValidateUtil.isAbsList(reList)) {
                return AjaxResult.successResult(reList.size(), reList);
            }
        }


        return AjaxResult.successResult(0, null);
    }


    /**
     * ----------------------------好管家-店铺下工人工作记录
     */
    //获取店铺里的工人工作记录
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/shop/postman/do/list")
    @ResponseBody
    public String order_postman_list(String token,
                                     String shopId,
                                     String postmanUsername,
                                     Integer orderType,
                                     String orderNo,
                                     Long startTime, Long endTime,
                                     Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有查询权限");
        }

        if (null == page) {
            page = 1;
        }
        if (null == size) {
            size = 20;
        }

        QueryCondition query = QueryCondition.getInstance();

        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);//所有未删除的
        if (ValidateUtil.isNotNull(postmanUsername)) {
            expression.addChild("postmanUsername", postmanUsername);
        }
        if (ValidateUtil.isNotNull(orderNo)) {
            expression.addChild("orderNo", orderNo);
        }
        if (ValidateUtil.isAbsLong(startTime) && startTime > 0) {
            expression.addChild("createTime", ">=", startTime);
        }
        if (ValidateUtil.isAbsLong(endTime) && endTime > 0) {
            expression.addChild("createTime", "<=", endTime);
        }
        if (null != orderType) {
            expression.addChild("orderType", orderType);
        }
        if (null != shopId) {
            expression.addChild("shopId", shopId);
        }
        query.addCondition(expression);
        query.setPage(page);
        query.setSize(size);
        query.addOrders("createTime", "desc");
        query.addOrders("orderNo", "desc");
        String sql = DaoUtils.getSql(PojoTables.OrderInfo, query);
        List<OrderInfo> list = null;
        int count = 0;
        try {
            if (!isNoCount) {
                count = UserDaoSql.getInstance().getCount(PojoTables.OrderInfo, query);
            }

            if (ValidateUtil.isAbsInteger(count) || isNoCount) {
                list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sql);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }

                OrderInfoVO vo = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), vo);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }


                voList.add(vo);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, count);
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }


    /**
     * -------------------------
     */
    //分页订单
    private List<OrderInfoVO> getList(List<OrderInfoVO> list, Long createTime, int size, int isLoadMore) {
        Boolean flag = false;//需不需要判断时间戳
        if (null != createTime && createTime > 0) {
            flag = true;
        }
        if (size <= 0) {
            size = 20;
        }
        if (null != list && list.size() > 0) {
            List<OrderInfoVO> orderInfoList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                OrderInfoVO orderInfo = list.get(i);
                if (null == orderInfo) {
                    continue;
                }

                if (flag) {//需要判断时间戳
                    if (0 == 1 - isLoadMore) {//加载更多
                        if (orderInfo.getCreateTime() < createTime) {
                            orderInfoList.add(orderInfo);
                        }
                    } else {
                        if (orderInfo.getCreateTime() > createTime) {
                            orderInfoList.add(orderInfo);
                        }
                    }
                } else {
                    orderInfoList.add(orderInfo);
                }
            }
            //排序订单，返回前size条
            orderInfoList = OrderListMan.sortVO(orderInfoList);
            List<OrderInfoVO> reList = new ArrayList<>();
            for (int i = 0; i < orderInfoList.size(); i++) {
                if (i < size) {
                    reList.add(orderInfoList.get(i));
                }
            }
            return reList;
        }

        return null;
    }

    // ----------------------------------------------城市代理

    // 获取进行中的订单V2 管理员（按代理获取订单）
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/ing/list/v2")
    @ResponseBody
    public String order_admin_ing_list_v2(String token, Integer orderType, Long agentId, @RequestParam(defaultValue = "0") Integer isGroupOrder, String city, String county, String region, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        //验证是否有权限
        if (!User.hasServiceAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        if (null == isGroupOrder) {
            isGroupOrder = 0;
        }
        List<OrderInfo> list = null;
        String cityStr = "";
        if (ValidateUtil.isNotNull(city)) {
            if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                if (JYPinyinHelper.isChinese(city)) {
                    city = JYPinyinHelper.toHanyuPinyin(city);
                } else {
                    city = city.toLowerCase();
                }
            }
            cityStr = " and a.shopCity='" + city + "'";
        }

        String orderTypeStr = "";
        if (null == orderType) {
            orderTypeStr = "";
        } else {
            if (0 == ORDER_TYPE.SERVICE_LOCK - orderType) {
                //如果是开锁订单
                orderTypeStr += " and orderStatus != " + ORDER_STATUS.PAYED;
                orderTypeStr += " and orderStatus != " + ORDER_STATUS.SUBMIT;
                orderTypeStr += " and orderStatus != " + ORDER_STATUS.POSTMAN_CANT_FINISH;
            }
            orderTypeStr += " and orderType = " + orderType;
        }
        String username = user.getUsername();
        if (user.getUserType() == UserType.COMPANY && SysCityCompanyMan.isAdminCompanyUser(username)) {
            username = SysCityCompanyMan.getSysCompanyOwnUsername(username);
            if (StringUtils.isEmpty(username)) {
                return AjaxResult.errorResult("代理为空");
            }
        }
        String groupOrder = "";
        if (isGroupOrder == 1) {
            groupOrder = " and a.orderType = " + ORDER_TYPE.GROUP_ORDER + " ";
        } else if (isGroupOrder == 0) {
            groupOrder = " and a.orderType != " + ORDER_TYPE.GROUP_ORDER + " ";
        }
        StringBuffer sb = new StringBuffer();
//        sb.append(" from ").append(PojoTables.OrderInfo)
//                .append(" a ")
//                .append(" LEFT JOIN ").append(PojoTables.SHOP_AGENT_RELATION).append(" b ON a.shopId = b.shopId ")
//                .append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append(" c ON c.agentId = b.agentId")
//                .append(" where b.id IS NOT NULL AND c.id IS NOT NULL AND a.delFlag = 0 AND b.delFlag =0 AND c.delFlag =0 and c.username ='").append(username).append("'")
//                .append(cityStr).append(orderTypeStr).append(groupOrder)
//                .append(" and (orderStatus!='").append(ORDER_STATUS.OVER).append("' and orderStatus!='").append(ORDER_STATUS.CANCEL)
//                .append("' and orderStatus!='").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append("' and orderStatus!='").append(ORDER_STATUS.PAYED_CANCEL)
//                .append("' and orderStatus!='").append(ORDER_STATUS.SHOP_REFUSED).append("' and orderStatus!='").append(ORDER_STATUS.SUBMIT)
//                .append("' and  orderStatus!='").append(ORDER_STATUS.PAYED)
//                .append("' ) ")
//                .append(" and (LEFT(orderNo,1) = 'M' or LEFT(orderNo,1) = 'P' or LEFT(orderNo,1) = '1' or LEFT(orderNo,1) = '2' or LEFT(orderNo,1) = '3' or LEFT(orderNo,1) = '4'  or LEFT(orderNo,1) = '5' ) ");
        sb.append(" from ").append(PojoTables.OrderInfo)
                .append(" a ")
                .append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append(" c ON c.agentId = a.agentId")
                .append(" where c.id IS NOT NULL AND a.delFlag = 0 AND  c.delFlag =0 and c.username ='").append(username).append("'")
                .append(cityStr).append(orderTypeStr).append(groupOrder)
                .append(" and (orderStatus!='").append(ORDER_STATUS.OVER).append("' and orderStatus!='").append(ORDER_STATUS.CANCEL)
                .append("' and orderStatus!='").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append("' and orderStatus!='").append(ORDER_STATUS.PAYED_CANCEL)
                .append("' and orderStatus!='").append(ORDER_STATUS.SHOP_REFUSED).append("' and orderStatus!='").append(ORDER_STATUS.SUBMIT)
                .append("' and  orderStatus!='").append(ORDER_STATUS.PAYED)
                .append("' and  orderStatus!='").append(ORDER_STATUS.ARRIVE_PAY)
                .append("' and  orderStatus!='").append(ORDER_STATUS.UNDERLINE_SUBMIT)
                .append("' ) ")
                .append(" and (LEFT(orderNo,1) = 'M' or LEFT(orderNo,1) = 'P' or LEFT(orderNo,1) = '1' or LEFT(orderNo,1) = '2' or LEFT(orderNo,1) = '3' or LEFT(orderNo,1) = '4'  or LEFT(orderNo,1) = '5' ) ");
        if (ValidateUtil.isID(agentId)) {
            sb.append(" and a.agentId =").append(agentId);
        }
        sb.append(" ORDER BY a.isUrgent desc,a.createTime DESC ");
        Long totalCount = 0l;
        try {
            if (!isNoCount) {
                StringBuffer sbCount = new StringBuffer();
                sbCount.append("select count(1) counts ").append(sb.toString());
                totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
            }

            if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select ")
                        .append(selectFiled)
                        .append(sb.toString())
                        .append(" LIMIT ").append((page - 1) * size).append(",").append(size);
                list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, totalCount);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }

    //获取已完成的订单V2 管理员（按代理获取订单）
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/finish/list/v2")
    @ResponseBody
    public String order_admin_finish_list_v2(String token, Integer orderType, Long agentId, @RequestParam(defaultValue = "0") Integer isGroupOrder, String city, String county, String region, Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        //验证是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }

        String orderTypeStr = "";
        if (null == orderType) {
            orderTypeStr = "";
        } else {
            if (0 == ORDER_TYPE.SERVICE_LOCK - orderType) {
                //如果是开锁订单
                orderTypeStr += " and a.orderStatus != " + ORDER_STATUS.PAYED;
            }
            orderTypeStr += " and a.orderType = " + orderType;
        }

        List<OrderInfo> list = null;
        String cityStr = "";
        if (ValidateUtil.isNotNull(city)) {
            if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                if (JYPinyinHelper.isChinese(city)) {
                    city = JYPinyinHelper.toHanyuPinyin(city);
                } else {
                    city = city.toLowerCase();
                }
            }
            cityStr = " and a.shopCity='" + city + "'";
        }

        String username = user.getUsername();
        if (UserType.COMPANY == user.getUserType() && SysCityCompanyMan.isAdminCompanyUser(user.getUsername())) {
            username = SysCityCompanyMan.getSysCompanyOwnUsername(username);
            if (StringUtils.isEmpty(username)) {
                return AjaxResult.errorResult("代理信息为空");
            }
        }
        String groupOrder = "";
        if (isGroupOrder == 1) {
            groupOrder = " and a.orderType = " + ORDER_TYPE.GROUP_ORDER + " ";
        } else if (isGroupOrder == 0) {
            groupOrder = " and a.orderType != " + ORDER_TYPE.GROUP_ORDER + " ";
        }
        StringBuffer sb = new StringBuffer();
        sb.append(" from ").append(PojoTables.OrderInfo).append(" a ")
//                .append(" LEFT JOIN shop_agent_relation b ON a.shopId = b.shopId ")
                .append(" LEFT JOIN user_agent_relation c ON c.agentId = a.agentId")
                .append(" where  c.id IS NOT NULL AND a.delFlag = 0 AND  c.delFlag =0 and c.username ='").append(username).append("'")
                .append(cityStr).append(orderTypeStr).append(groupOrder)
                // .append(" and (LEFT(a.orderNo,1) = 'M' or LEFT(a.orderNo,1) = 'P' or LEFT(a.orderNo,1) = '1' or LEFT(a.orderNo,1) = '2') ")
                //Jahnke 2020年9月11日 11:28:08 判断开头
                .append("  AND (a.orderNo LIKE '1%' OR a.orderNo LIKE '2%' OR a.orderNo LIKE 'M%' OR a.orderNo LIKE 'P%')\n")
                .append(" and orderStatus =  ").append(ORDER_STATUS.OVER); // 只看已完成订单
//                .append(" and  (orderStatus='").append(ORDER_STATUS.OVER).append("' OR orderStatus='").append(ORDER_STATUS.CANCEL)
//                .append("' OR orderStatus='").append(ORDER_STATUS.CANCEL_BY_SYSTEM).append("' OR orderStatus='").append(ORDER_STATUS.PAYED_CANCEL)
//                .append("' ) ")
        if (ValidateUtil.isID(agentId)) {
            sb.append(" and a.agentId =").append(agentId);
        }
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
            sb.append(" and a.createTime  BETWEEN  ").append(startTime).append(" and  ").append(endTime);
        } else {
            long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
            if (ValidateUtil.isAbsLong(pointTime)) {
                sb.append(" and a.createTime > ").append(pointTime).append(" ");
            }
        }

        Long totalCount = 0l;
        try {
            if (!isNoCount) {
                StringBuffer sbCount = new StringBuffer();
                sbCount.append("select count(1) counts ").append(sb.toString());
                totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
            }

            if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select ")
//                    .append(" a.orderNo,a.parentOrderNo,a.orderType,a.dispatchState,a.username,a.rePayUsername,a.orderStatus,a.shopId,a.squareShopId,a.shopName,a.totalCount,a.totalPrice,a.totalWeight,a.isPaid,a.payType,a.payType2,a.payTime,a.isRefundApply,a.isPartCancelApply,a.groupState,a.isGroupOrder,a.isZiQu,a.ziQuTime,a.postmanUsername,a.note,a.shopCity,a.agentId,a.buyer,a.telephone,a.lat,a.lng,a.province,a.city,a.county,a.address,a.address2,a.shopPhone,a.shopSelfPost,a.shopSureBySys,a.postmanSureBySys,a.postmanName,a.postmanPhone,a.preDayNo,a.isAppointment,a.isArrivePay,a.isSpecifiedPostmen,a.isComment,a.shopImageUrl,a.shopAddress,a.shopLat,a.shopLng,a.postmanImageUrl,a.isSeriesSaleShop,a.secondaryPostManUsername,a.secondaryPostmanName,a.secondaryPostmanPhone,a.secondaryPostmanImageUrl,a.secondaryPostmanSureTime,a.secondaryPostmanPullTime,a.postmanPostPointTime,a.payOrderNo,a.refundNo,a.isBackStock,a.postmanFinishTime,a.postFailReason ")
                        .append(selectFiled)
                        .append(sb.toString())
                        .append(" ORDER BY a.createTime DESC ")
                        .append(" LIMIT ").append((page - 1) * size).append(",").append(size);
                list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, totalCount);
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //获取全部订单V2 管理员（按代理获取订单）
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/all/list/v2")
    @ResponseBody
    public String order_admin_all_list_v2(String token, Integer orderType, Long agentId, @RequestParam(defaultValue = "0") Integer isGroupOrder, String city, String county, String region, Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }
        //验证是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }

        String orderTypeStr = "";
        if (null == orderType) {
            orderTypeStr = "";
        } else {
            if (0 == ORDER_TYPE.SERVICE_LOCK - orderType) {
                //如果是开锁订单
                orderTypeStr += " and a.orderStatus != " + ORDER_STATUS.PAYED;
            }
            orderTypeStr += " and a.orderType = " + orderType;
        }

        List<OrderInfo> list = null;
        String cityStr = "";
        if (ValidateUtil.isNotNull(city)) {
            if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                if (JYPinyinHelper.isChinese(city)) {
                    city = JYPinyinHelper.toHanyuPinyin(city);
                } else {
                    city = city.toLowerCase();
                }
            }
            cityStr = " and a.shopCity='" + city + "'";
        }
        String username = user.getUsername();
        if (UserType.COMPANY == user.getUserType() && SysCityCompanyMan.isAdminCompanyUser(user.getUsername())) {
            username = SysCityCompanyMan.getSysCompanyOwnUsername(username);
            if (StringUtils.isEmpty(username)) {
                return AjaxResult.errorResult("代理信息为空");
            }
        }

        String groupOrder = "";
        if (isGroupOrder == 1) {
            groupOrder = " and a.orderType = " + ORDER_TYPE.GROUP_ORDER + " ";
        } else if (isGroupOrder == 0) {
            groupOrder = " and a.orderType != " + ORDER_TYPE.GROUP_ORDER + " ";
        }
        StringBuffer sb = new StringBuffer();
        sb.append(" from ").append(PojoTables.OrderInfo).append(" a ")
//                .append(" LEFT JOIN ").append(PojoTables.SHOP_AGENT_RELATION).append(" b ON a.shopId = b.shopId ")
                .append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append(" c ON c.agentId = a.agentId")
                .append(" where  c.id IS NOT NULL AND a.delFlag = 0  AND c.delFlag =0 and c.username ='").append(username).append("'")
                .append(cityStr).append(orderTypeStr).append(groupOrder);
        if (ValidateUtil.isID(agentId)) {
            sb.append(" and a.agentId =").append(agentId);
        }
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
            sb.append(" and a.createTime  BETWEEN  ").append(startTime).append(" and  ").append(endTime);
        } else {
            long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
            if (ValidateUtil.isAbsLong(pointTime)) {
                sb.append(" and a.createTime > ").append(pointTime).append(" ");
            }
        }

        Long totalCount = 0l;
        try {
            if (!isNoCount) {
                StringBuffer sbCount = new StringBuffer();
                sbCount.append("select count(1) counts ").append(sb.toString());
                totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
            }

            if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                StringBuffer sbSql = new StringBuffer();
//            sbSql.append("select a.* ")
                sbSql.append("select ")
                        .append(selectFiled)
                        .append(sb.toString())
                        .append(" ORDER BY a.createTime DESC ")
                        .append(" LIMIT ").append((page - 1) * size).append(",").append(size);
                list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询失败，请稍后再试");
        }

//        QueryCondition query = QueryCondition.getInstance();
//        Expression expression = Expression.getInstance();
//        expression.addChild("delFlag", 0);//所有未删除的
//        if (ValidateUtil.isNotNull(city)) {
//            expression.addChild("shopCity", city);
//        }
//        if (null != orderType) {
//            expression.addChild("orderType", orderType);
//        }
//        query.addCondition(expression);
//        query.addOrders("createTime", "desc");
//        query.setPage(page);
//        query.setSize(size);
//        String sql = DaoUtils.getSql(PojoTables.OrderInfo, query);
//        String sqlCount = DaoUtils.getSqlCount(PojoTables.OrderInfo, query);
//        List<OrderInfo> list = null;
//        long totalCount = 0L;
//        try {
//            list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sql);
//            totalCount = UserDaoSql.getInstance().getCount(sqlCount);
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }


        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = OrderListMan.convertToVo(list, false);
            if (ValidateUtil.isAbsList(voList)) {
                // 系统派单，自动接单
                voList = voList.stream().map(l -> postStatus(l)).collect(Collectors.toList());
                // 转接单
                Set<String> tmpSet = new HashSet<>();
                for (OrderInfoVO o : voList) {
                    tmpSet.add(o.getOrderNo());
                }
                List<HashMap<String, Object>> opList = getOrderPostman(tmpSet);
                if (null != opList) {
                    voList = voList.stream().map(v -> getPost(v, opList)).collect(Collectors.toList());
                }
                return AjaxResult.successResult(voList, totalCount);
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //订单查询V2 管理员（按代理获取订单）
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/search/list/v2")
    @ResponseBody
    public String order_admin_list_v2(String token,
                                      String city, Integer orderType,
                                      Integer isSquareOrder,   //  是否是创业商圈订单
                                      String shopName,
                                      String name, String phone, String address, //购买人信息
                                      String orderNo, //订单编号
                                      @RequestParam(defaultValue = "0") Integer isGroupOrder, // 团购订单
                                      @RequestParam(defaultValue = "-1") Integer isZiQu, // 取货方式(-1全部 0配送 1自取 2到店堂食 3精选直邮)
                                      Integer orderStatus,//订单状态
                                      Integer orderOverTime, // 超时订单
                                      Integer orderBadOverTime, // 严重超时订单
                                      Long shopId,//店铺ID
                                      Long agentId, // 商圈
                                      Long startTime, Long endTime,
                                      Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证用户是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }

        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }

        // 订单类型
        String orderTypeStr = "";
        if (ValidateUtil.isAbsInteger(orderType)) {
            orderTypeStr = " and a.orderType=" + orderType;
        }
        // 城市
        String cityStr = "";
        if (ValidateUtil.isNotNull(city)) {
            if (null != SYS_SETTINGS.HAS_MULTILINGUAL && 0 == 1 - SYS_SETTINGS.HAS_MULTILINGUAL) {
                if (JYPinyinHelper.isChinese(city)) {
                    city = JYPinyinHelper.toHanyuPinyin(city);
                } else {
                    city = city.toLowerCase();
                }
            }
            cityStr = " and a.shopCity='" + city + "'";
        }

        // 店铺信息
        String shopIdStr = "";
        String shopNameStr = "";

        if (ValidateUtil.isAbsLong(shopId)) {
            shopIdStr = " and a.shopId='" + shopId + "'";
        }
        if (ValidateUtil.isNotNull(shopName)) {
            shopNameStr = " and a.shopName like '%" + shopName + "%'";
        }

        // 购买人信息
        String nameStr = "";
        String phoneStr = "";
        String addressStr = "";
        String orderNoStr = "";
        String orderStatusStr = "";
        String timeStr = "";
        if (ValidateUtil.isNotNull(name)) {
            nameStr = " and a.buyer like '%" + name + "%'";
        }
        if (ValidateUtil.isNotNull(phone)) {
            phoneStr = " and a.telephone like '%" + phone + "%'";
        }
        if (ValidateUtil.isNotNull(address)) {
            addressStr = " and ( a.address like '%" + address + "%' or a.address2 like '%" + address + "%' )";
        }
        if (ValidateUtil.isNotNull(orderNo)) {
            orderNoStr = " and a.orderNo like '%" + orderNo + "%'";
        }
        String chaoshi = "";
        if (null != orderOverTime && orderOverTime == 1) {
            chaoshi = " and a.orderStatus=9 and ((a.ziQuTime > 0 and a.postmanFinishTime-a.ziQuTime>0) or (a.ziQuTime =0 and a.postmanFinishTime-a.createTime > a.agentPostmanOverTime*60*1000)) ";
        }
        String yzChaoshi = "";
        if (null != orderBadOverTime && orderBadOverTime == 1) {
            yzChaoshi = " and a.orderStatus=9 and ((a.ziQuTime > 0 and a.postmanFinishTime-a.ziQuTime>30 * 60 * 1000) " +
                    " or (a.ziQuTime=0 and a.postmanFinishTime-a.createTime > (a.agentPostmanOverTime+30)*60*1000)) ";
        }
        if (null != orderStatus && orderStatus > 0) {
            orderStatusStr = " and a.orderStatus = " + orderStatus;
        }
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
            timeStr = " and a.createTime Between  " + startTime + " and " + endTime;
        } else {
            long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
            if (ValidateUtil.isAbsLong(pointTime)) {
                timeStr = " and  a.createTime > " + pointTime + " ";
            }
        }
        String cityAdminUsername = user.getUsername();
        if (UserType.COMPANY == user.getUserType() && SysCityCompanyMan.isAdminCompanyUser(user.getUsername())) {
            cityAdminUsername = SysCityCompanyMan.getSysCompanyOwnUsername(cityAdminUsername);
            if (StringUtils.isEmpty(cityAdminUsername)) {
                return AjaxResult.errorResult("代理信息为空");
            }
        }

        String groupOrder = "";
        if (isGroupOrder == 1) {
            groupOrder = " and a.orderType = " + ORDER_TYPE.GROUP_ORDER + " ";
        } else if (isGroupOrder == 0) {
            groupOrder = " and a.orderType != " + ORDER_TYPE.GROUP_ORDER + " ";
        }
        if (isSquareOrder != null && isSquareOrder == 1) {
            groupOrder += " and a.orderNo like 'P%'";
        }
        String ziQu = "";
        if (null != isZiQu && isZiQu != -1) {
            ziQu = " and a.isZiQu = " + isZiQu + " ";
        }
        StringBuffer sb = new StringBuffer();
//        sb.append(" from ").append(PojoTables.OrderInfo)
//                .append(" a LEFT JOIN shop_agent_relation b ON a.shopId = b.shopId ")
//                .append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append(" c ON c.agentId = b.agentId")
//                .append(" where b.id IS NOT NULL AND c.id IS NOT NULL AND a.delFlag = 0 AND b.delFlag =0 AND c.delFlag =0 and c.username ='").append(cityAdminUsername).append("'")
//                .append(cityStr).append(orderTypeStr).append(groupOrder).append(shopIdStr).append(chaoshi).append(yzChaoshi)
//                .append(shopNameStr).append(nameStr).append(phoneStr).append(addressStr).append(orderNoStr).append(orderStatusStr)
//                .append(timeStr).append(ziQu);

        sb.append(" from ").append(PojoTables.OrderInfo).append(" a ")
//                .append(" LEFT JOIN ").append(PojoTables.SHOP_AGENT_RELATION).append(" b ON a.shopId = b.shopId ")
                .append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append(" c ON c.agentId = a.agentId")
                .append(" where c.id IS NOT NULL AND a.delFlag = 0 AND c.delFlag =0 and c.username ='").append(cityAdminUsername).append("'")
                .append(cityStr).append(orderTypeStr).append(groupOrder).append(shopIdStr).append(chaoshi).append(yzChaoshi)
                .append(shopNameStr).append(nameStr).append(phoneStr).append(addressStr).append(orderNoStr).append(orderStatusStr)
                .append(timeStr).append(ziQu);
        if (ValidateUtil.isID(agentId)) {
            sb.append(" and a.agentId = ").append(agentId);
        }
        sb.append(" ORDER BY a.createTime DESC ");
        Long totalCount = 0l;

        if (!isNoCount) {
            try {
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select count(a.orderNo) as counts ");
                sbSql.append(sb.toString());
                totalCount = UserDaoSql.getInstance().getCount(sbSql.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                totalCount = 0l;
            }
        }


        List<OrderInfo> list = new ArrayList<>();
        List<HashMap<String, Object>> listMap = null;
        if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
            try {
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select  a.orderNo ");
                sbSql.append(sb.toString());
                sbSql.append(" limit ").append((page - 1) * size).append(",").append(size);
                listMap = UserDaoSql.getInstance().queryBySql(sbSql.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                listMap = null;
            }
        }

        if (ValidateUtil.isAbsList(listMap)) {
            for (int i = 0; i < listMap.size(); i++) {
                if (null == listMap.get(i)) {
                    continue;
                }
                String no = (String) listMap.get(i).get("orderNo");
                if (ValidateUtil.isNull(no)) {
                    continue;
                }
                OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(no);
                if (null == orderInfo) {
                    continue;
                }
                list.add(orderInfo);
            }
        }

        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = new OrderInfoVO();
                BeanUtils.copyProperties(list.get(i), orderInfoVO);
                // try {
                //     ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                // } catch (Exception e) {
                //     e.printStackTrace();
                //     continue;
                // }
                // if (null == orderInfoVO) {
                //     continue;
                // }
                if (ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }

                voList.add(orderInfoVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                // 系统派单，自动接单
                voList = voList.stream().map(l -> postStatus(l)).collect(Collectors.toList());
                // 转接单
                Set<String> tmpSet = new HashSet<>();
                for (OrderInfoVO o : voList) {
                    tmpSet.add(o.getOrderNo());
                }
                List<HashMap<String, Object>> opList = getOrderPostman(tmpSet);
                if (null != opList) {
                    voList = voList.stream().map(v -> getPost(v, opList)).collect(Collectors.toList());
                }
                return AjaxResult.successResult(voList, totalCount);
            }
        }
        return AjaxResult.successResult(null, 0);
    }

    /**
     * 搜索订单
     * //1.时间
     * //2.省市区
     * //
     * //3.订单号
     * //
     * //4.商家
     * //
     * //5.订单状态
     * //订单查询V2 管理员（按代理获取订单）
     * //queryType 1.商家超时未送达  2.骑手超时未取货  3.骑手超时未送达
     */
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/search/list/v3")
    @ResponseBody
    public String order_admin_list_v2(String token,
                                      String province,
                                      String city,
                                      String county,
                                      Integer orderType,
                                      String orderNo, //订单编号
                                      Integer orderStatus,//订单状态
                                      Long shopId,//店铺ID
                                      Integer queryType,   // 查询异常类型
                                      Integer isGroupOrder,
                                      Long startTime, Long endTime,
                                      Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        //验证用户是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }

        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }

        // 城代或配送公司
        String agentIdStr = "";

        StringBuffer sbWhere = new StringBuffer();
        sbWhere.append(" aa.delFlag = 0").append(agentIdStr);
        if (null != isGroupOrder && isGroupOrder == 1) {
            sbWhere.append(" and aa.isGroupOrder=1 ");
        }
        if (StringUtils.isNotEmpty(province)) {
            sbWhere.append(" and aa.province = '").append(province).append("'");
        }
        if (StringUtils.isNotEmpty(city)) {
            sbWhere.append(" and (aa.city = '").append(city).append("' or aa.shopCity = '").append(city).append("') ");
        }
        if (StringUtils.isNotEmpty(county)) {
            sbWhere.append(" and aa.county = '").append(county).append("' ");
        }
        if (StringUtils.isNotEmpty(orderNo)) {
            sbWhere.append(" and aa.orderNo like ").append("'%").append(orderNo).append("%'");
        }
        if (orderType != null) {
            sbWhere.append(" and aa.orderType = ").append(orderType);
        }
        if (orderStatus != null) {
            sbWhere.append(" and aa.orderStatus = ").append(orderStatus);
        }
        if (shopId != null) {
            sbWhere.append(" and aa.shopId = ").append(shopId);
        }
        if (queryType == null) {
            queryType = 0;
        }
        switch (queryType) {
            case 1: {
                // 商家超时未送达
                sbWhere.append(" and aa.shopFinishTime-aa.shopSureTime > aa.agentShopOverTime");
            }
            break;
            case 2: {
                // 骑手超时未取货
                sbWhere.append(" and aa.postmanPullTime-aa.postmanSureTime > aa.agentNotTakenOrderTime");
            }
            break;
            case 3: {
                // 骑手超时未送达
                sbWhere.append(" and postmanFinishTime-postmanSureTime > agentPostmanOverTime");
            }
            break;
        }
        if (ValidateUtil.isAbsLong(startTime)) {
            sbWhere.append(" and aa.createTime >=").append(startTime);
        }
        if (ValidateUtil.isAbsLong(endTime)) {
            sbWhere.append(" and aa.createTime <=").append(endTime);
        }
        if (ValidateUtil.isNotAbsLong(startTime) && ValidateUtil.isNotAbsLong(endTime)) {
            long pointTime = OrderMan.getDefaultQueryOrderTimePoint();
            if (ValidateUtil.isAbsLong(pointTime)) {
                sbWhere.append(" and aa.createTime >").append(pointTime);
            }
        }

        String t_order_info = PojoTables.OrderInfo;
        if (null != SYS_SETTINGS.USE_BAK_ORDER && 0 == 1 - SYS_SETTINGS.USE_BAK_ORDER) {
            boolean needUnion = false;
            String u_order_info = PojoTables.OrderInfo;
            String d_order_info = null;
            String dataDbName = OrderBakTaskUtils.getDataDbName();
            if (ValidateUtil.isNotNull(dataDbName)) {
                d_order_info = dataDbName + "." + PojoTables.D_ORDER_INFO;
            }
            if (ValidateUtil.isAbsLong(endTime) || ValidateUtil.isAbsLong(startTime)) {
                Long sec = DateUtils.getPreDaysOfTimestamp(Long.parseLong(OrderBakTaskUtils.autoBackDays + ""));
                if (ValidateUtil.isAbsLong(endTime) && endTime < sec) {
                    // 查询的是备份时间里的
                    t_order_info = d_order_info + " aa ";
                } else if (ValidateUtil.isAbsLong(startTime) && startTime > sec) {
                    // 查询的是还没备份时间里的
                    t_order_info = t_order_info + " aa ";
                } else {
                    // 需要联合查询
                    needUnion = true;
                }
            } else {
                // 需要两表连接查询
                needUnion = true;
            }
            if (needUnion) {
                StringBuffer sb = new StringBuffer();

                sb.append(" select a.* from (" +
                        "  SELECT 1 tt,id,createTime FROM " + d_order_info + "  aa WHERE NOT EXISTS(SELECT * FROM " + u_order_info + " b WHERE aa.orderNo=b.orderNo) " +
                        "   and " + sbWhere.toString() +
                        " UNION " +
                        "  SELECT 0 tt,id,createTime FROM " + u_order_info + " aa " +
                        "   where " + sbWhere.toString() +
                        " ORDER BY createTime DESC ");
                sb.append(" limit ").append((page - 1) * size).append(",").append(size);

                sb.append(" ) tb " +
                        " left join " + d_order_info + " a on a.id = tb.id where tt=1 ");
                sb.append(" union ");
                sb.append("  select a.* from (" +
                        "  SELECT 1 tt,id,createTime FROM " + d_order_info + "  aa WHERE NOT EXISTS(SELECT * FROM " + u_order_info + " b WHERE aa.orderNo=b.orderNo) " +
                        "   and " + sbWhere.toString() +
                        " UNION " +
                        "  SELECT 0 tt,id,createTime FROM " + u_order_info + " aa " +
                        "   where " + sbWhere.toString() +
                        " ORDER BY createTime DESC ");

                sb.append(" limit ").append((page - 1) * size).append(",").append(size);

                sb.append(" ) tb ");
                sb.append(" left join " + u_order_info + " a on a.id = tb.id where tt=0 ");

                // 查询数据
                List<OrderInfo> list = null;
                try {
                    StringBuffer sbSql = new StringBuffer();
                    sbSql.append("select  aa.* ");
                    sbSql.append(" from ( ").append(sb).append(" ) aa ");
                    list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    list = null;
                }


                if (ValidateUtil.isAbsList(list)) {
                    List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
                    for (int i = 0; i < list.size(); i++) {
                        if (null == list.get(i)) {
                            continue;
                        }
                        OrderInfoVO orderInfoVO = new OrderInfoVO();
                        list.get(i).setGoods(OrderGoodsMemory.getInstance().listOfOrderNo(list.get(i).getOrderNo()));
                        try {
                            ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                        } catch (Exception e) {
                            e.printStackTrace();
                            continue;
                        }
                        if (null == orderInfoVO) {
                            continue;
                        }
                        if (ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                            orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                        }
                        voList.add(orderInfoVO);
                    }

                    StringBuffer sbCountTmp = new StringBuffer();
                    // 查询数量
                    Long totalCount = 0L;
                    try {
                        StringBuffer sbSql = new StringBuffer();
                        sbSql.append("SELECT COUNT(1) as counts FROM " + d_order_info + " aa WHERE NOT EXISTS(SELECT * FROM " + u_order_info + " b WHERE aa.orderNo=b.orderNo)    AND  ").append(sbWhere);
                        Long time = DateUtils.getCurrTime();
                        Long totalCountD = UserDaoSql.getInstance().getCount(sbSql.toString());
                        if (ValidateUtil.isNotAbsLong(totalCountD)) {
                            totalCountD = 0l;
                        }

                        StringBuffer sbSqlU = new StringBuffer();
                        sbSqlU.append("SELECT COUNT(1) as counts FROM " + u_order_info + " aa WHERE ").append(sbWhere);
                        Long time3 = DateUtils.getCurrTime();
                        Long totalCountU = UserDaoSql.getInstance().getCount(sbSqlU.toString());
                        if (ValidateUtil.isNotAbsLong(totalCountU)) {
                            totalCountU = 0l;
                        }
                        totalCount = totalCountU + totalCountD;
                    } catch (Exception e) {
                        e.printStackTrace();
                        totalCount = 0L;
                    }

                    if (ValidateUtil.isAbsList(voList)) {
                        return AjaxResult.successResult(voList, totalCount);
                    }
                } else {
                    return AjaxResult.successResult(0, 0, null);
                }

            }
        } else {
            t_order_info = t_order_info + " aa ";
        }


//        StringBuilder sql = new StringBuilder();
//        sql.append(" from ").append(t_order_info).append(" where aa.delFlag = 0").append(agentIdStr);
//        if (null != isGroupOrder && isGroupOrder == 1) {
//            sql.append(" and aa.isGroupOrder=1 ");
//        }
//        if (StringUtils.isNotEmpty(province)) {
//            sql.append(" and aa.province = '").append(province).append("'");
//        }
//        if (StringUtils.isNotEmpty(city)) {
//            sql.append(" and (aa.city = '").append(city).append("' or aa.shopCity = '").append(city).append("') ");
//        }
//        if (StringUtils.isNotEmpty(county)) {
//            sql.append(" and aa.county = '").append(county).append("' ");
//        }
//        if (StringUtils.isNotEmpty(orderNo)) {
//            sql.append(" and aa.orderNo like ").append("'%").append(orderNo).append("%'");
//        }
//        if (orderType != null) {
//            sql.append(" and aa.orderType = ").append(orderType);
//        }
//        if (orderStatus != null) {
//            sql.append(" and aa.orderStatus = ").append(orderStatus);
//        }
//        if (shopId != null) {
//            sql.append(" and aa.shopId = ").append(shopId);
//        }
//        if (queryType == null) {
//            queryType = 0;
//        }
//        switch (queryType) {
//            case 1: {
//                // 商家超时未送达
//                sql.append(" and aa.shopFinishTime-aa.shopSureTime > aa.agentShopOverTime");
//            }
//            break;
//            case 2: {
//                // 骑手超时未取货
//                sql.append(" and aa.postmanPullTime-aa.postmanSureTime > aa.agentNotTakenOrderTime");
//            }
//            break;
//            case 3: {
//                // 骑手超时未送达
//                sql.append(" and postmanFinishTime-postmanSureTime > agentPostmanOverTime");
//            }
//            break;
//        }
//        if (ValidateUtil.isAbsLong(startTime)) {
//            sql.append(" and aa.createTime >=").append(startTime);
//        }
//        if (ValidateUtil.isAbsLong(endTime)) {
//            sql.append(" and aa.createTime <=").append(endTime);
//        }

        StringBuilder sbFrom = new StringBuilder();
        sbFrom.append(" from ").append(t_order_info).append(" where  ").append(sbWhere);

        // 查询数量
        Long totalCount = 0L;
        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("select count(aa.orderNo) as counts ");
            sbSql.append(sbFrom.toString());
            totalCount = UserDaoSql.getInstance().getCount(sbSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            totalCount = 0L;
        }

        // 查询数据
        List<OrderInfo> list = null;
        try {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("select  aa.* ");
            sbSql.append(sbFrom.toString()).append(" order by aa.createTime desc ");
            sbSql.append(" limit ").append((page - 1) * size).append(",").append(size);
            list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            list = null;
        }


        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = new OrderInfoVO();
                list.get(i).setGoods(OrderGoodsMemory.getInstance().listOfOrderNo(list.get(i).getOrderNo()));
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoVO) {
                    continue;
                }
                if (ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }
                voList.add(orderInfoVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, totalCount);
            }
        }

//
//        // 城代或配送公司
//        String agentIdStr = "";
//        if ((user.getUserType() == UserType.ADMIN || SysCityCompanyMan.isAdminCompanyUser(user.getUsername())) && SysCityAdminMan.isUpperLowerSysAdmin()) {
//            String sysCityAdminUsername = user.getUsername();
//            if (user.getUserType() == UserType.COMPANY) {
//                sysCityAdminUsername = SysCityCompanyMan.getSysCompanyOwnUsername(sysCityAdminUsername);
//            }
//            List<SysCityAdmin> sysCityAdminList = SysCityAdminMemory.getInstance().listOfUsername(sysCityAdminUsername);
////            List<SysCityAdmin> sysCityAdminList = SysCityAdminMemory.getInstance().listOfUsername(user.getUsername());
//            if (sysCityAdminList == null || sysCityAdminList.size() == 0) {
//                return AjaxResult.successResult(0, 0, null);
//            }
//            // 代理
//            Set<Long> agentIdSet = StatisCityAdminMan.listOfCityAgentIdBySysAdminId(sysCityAdminList.get(0).getId(), true, false, true);
//            if (agentIdSet == null || agentIdSet.size() == 0) {
//                return AjaxResult.successResult(0, 0, null);
//            }
//            String temp = StatisCityAdminMan.setTransformToList(agentIdSet);
//            if (StringUtils.isEmpty(temp)) {
//                return AjaxResult.successResult(0, 0, null);
//            }
//            agentIdStr = " and agentId in " + temp;
//        }
//
//
//        StringBuilder sql = new StringBuilder();
//        sql.append(" from ").append(PojoTables.OrderInfo).append(" where delFlag = 0").append(agentIdStr);
//        if (null != isGroupOrder && isGroupOrder == 1) {
//            sql.append(" and isGroupOrder=1 ");
//        }
//        if (StringUtils.isNotEmpty(province)) {
//            sql.append(" and province = '").append(province).append("'");
//        }
//        if (StringUtils.isNotEmpty(city)) {
//            sql.append(" and (city = '").append(city).append("' or shopCity = '").append(city).append("') ");
//        }
//        if (StringUtils.isNotEmpty(county)) {
//            sql.append(" and county = '").append(county).append("' ");
//        }
//        if (StringUtils.isNotEmpty(orderNo)) {
//            sql.append(" and orderNo like ").append("'%").append(orderNo).append("%'");
//        }
//        if (orderType != null) {
//            sql.append(" and orderType = ").append(orderType);
//        }
//        if (orderStatus != null) {
//            sql.append(" and orderStatus = ").append(orderStatus);
//        }
//        if (shopId != null) {
//            sql.append(" and shopId = ").append(shopId);
//        }
//        if (queryType == null) {
//            queryType = 0;
//        }
//        switch (queryType) {
//            case 1: {
//                // 商家超时未送达
//                sql.append(" and shopFinishTime-shopSureTime > agentShopOverTime");
//            }
//            break;
//            case 2: {
//                // 骑手超时未取货
//                sql.append(" and postmanPullTime-postmanSureTime > agentNotTakenOrderTime");
//            }
//            break;
//            case 3: {
//                // 骑手超时未送达
//                sql.append(" and postmanFinishTime-postmanSureTime > agentPostmanOverTime");
//            }
//            break;
//        }
////        if (queryType == 1) {
////            // 商家超时未送达
////            sql.append(" and shopFinishTime-shopSureTime > agentShopOverTime");
////        }
////        if (queryType == 2) {
////            // 骑手超时未取货
////            sql.append(" and postmanPullTime-postmanSureTime > agentNotTakenOrderTime");
////        }
////        if (queryType == 3) {
////            // 骑手超时未送达
////            sql.append(" and postmanFinishTime-postmanSureTime > agentPostmanOverTime");
////        }
//        if (ValidateUtil.isAbsLong(startTime)) {
//            sql.append(" and createTime >=").append(startTime);
//        }
//        if (ValidateUtil.isAbsLong(endTime)) {
//            sql.append(" and createTime <=").append(endTime);
//        }
//
//        // 查询数量
//        Long totalCount = 0L;
//        try {
//            StringBuffer sbSql = new StringBuffer();
//            sbSql.append("select count(orderNo) as counts ");
//            sbSql.append(sql.toString());
//            totalCount = UserDaoSql.getInstance().getCount(sbSql.toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//            totalCount = 0L;
//        }
//
//        // 查询数据
//        List<OrderInfo> list = null;
//        try {
//            StringBuffer sbSql = new StringBuffer();
//            sbSql.append("select  * ");
//            sbSql.append(sql.toString()).append(" order by id desc ");
//            sbSql.append(" limit ").append((page - 1) * size).append(",").append(size);
//            list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sbSql.toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//            list = null;
//        }
//        if (ValidateUtil.isAbsList(list)) {
//            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
//            for (int i = 0; i < list.size(); i++) {
//                if (null == list.get(i)) {
//                    continue;
//                }
//                OrderInfoVO orderInfoVO = new OrderInfoVO();
//                list.get(i).setGoods(OrderGoodsMemory.getInstance().listOfOrderNo(list.get(i).getOrderNo()));
//                try {
//                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    continue;
//                }
//                if (null == orderInfoVO) {
//                    continue;
//                }
//                if (ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
//                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
//                }
//                voList.add(orderInfoVO);
//            }
//
//            if (ValidateUtil.isAbsList(voList)) {
//                return AjaxResult.successResult(totalCount, voList.size(), voList);
//            }
////        if (ValidateUtil.isAbsList(list)) {
////            return AjaxResult.successResult(totalCount, list.size(), list);
////        }
//        }
        return AjaxResult.successResult(0, 0, null);
    }

    // 团购核销记录
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/group/finsh/list")
    @ResponseBody
    public String order_group_list_v2(String token,
                                      String province,
                                      String city,
                                      String county,
                                      Integer isGroupOrder,
                                      String orderNo, //订单编号
                                      Long shopId,//店铺ID
                                      Long startTime, Long endTime,
                                      Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
//        验证用户是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }

        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        String agentIdStr = "";

        StringBuilder sql = new StringBuilder();
        sql.append(" from ").append(PojoTables.OrderInfo).append(" ori ")
                .append(" left join ").append(PojoTables.OrderPay).append(" orp on ori.orderNo = orp.orderNo and orp.delFlag = 0 ")
                .append(" left join ").append(PojoTables.OrderGoods).append(" org on org.orderNo = ori.orderNo and org.delFlag = 0 ")
                .append(" left join ").append(PojoTables.ShopInfo).append(" si on si.id = ori.shopId and si.delFlag = 0 ")
//                .append(" left join ").append(PojoTables.SHOP_AGENT_RELATION).append(" sar on sar.shopId=si.id and sar.delFlag=0")
                .append(" left join ").append(PojoTables.USER_AGENT_RELATION).append(" uar on uar.agentId=ori.agentId and uar.delFlag=0")
                .append(" where ori.delFlag = 0 and ori.orderStatus = 9 ").append(agentIdStr);
        if (null != isGroupOrder && isGroupOrder == 1) {
            sql.append(" and ori.orderType= ").append(ORDER_TYPE.GROUP_ORDER).append(" ");
        }
        if (user.getUserType() == UserType.ADMIN) {
            sql.append(" and uar.username= '").append(user.getUsername()).append("' ");
        }
        if (StringUtils.isNotEmpty(province)) {
            sql.append(" and si.province like ").append("'%").append(province).append("%'");
        }
        if (StringUtils.isNotEmpty(city)) {
            sql.append(" and si.city like ").append("'%").append(city).append("%'");
        }
        if (StringUtils.isNotEmpty(county)) {
            sql.append(" and si.county like ").append("'%").append(county).append("%'");
        }
        if (StringUtils.isNotEmpty(orderNo)) {
            sql.append(" and ori.orderNo like ").append("'%").append(orderNo).append("%'");
        }

        if (shopId != null) {
            sql.append(" and ori.shopId = ").append(shopId);
        }
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" and ori.createTime >=").append(startTime);
        }
        if (ValidateUtil.isAbsLong(endTime)) {
            sql.append(" and ori.createTime <=").append(endTime);
        }
        Long totalCount = 0L;
        if (!isNoCount) {
            try {
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select count(ori.orderNo) as counts ");
                sbSql.append(sql.toString());
                totalCount = UserDaoSql.getInstance().getCount(sbSql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                totalCount = 0L;
            }
        }

        List<HashMap<String, Object>> list = null;

        if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
            try {
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("select  ori.*,IFNULL(orp.shopMoney,0) shopMoney,IFNULL(orp.platformMoney,0) platformMoney," +
                        "IFNULL(orp.squareMoney,0) squareMoney," +
                        "IFNULL(orp.cityAdminMoney,0) cityAdminMoney," +
                        "IFNULL(orp.cityAdminMoney1,0) cityAdminMoney1," +
                        "IFNULL(orp.cityAdminMoney2,0) cityAdminMoney2," +
                        "IFNULL(orp.cityAdminMoney3,0) cityAdminMoney3," +
                        "IFNULL(orp.cityAdminMoney4,0) cityAdminMoney4," +
                        "org.name as goodsName ");
                sbSql.append(sql.toString()).append(" order by ori.id desc ");
                sbSql.append(" limit ").append((page - 1) * size).append(",").append(size);
                list = UserDaoSql.getInstance().queryBySql(sbSql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                list = null;
            }
        }

        if (ValidateUtil.isAbsList(list)) {
            if (ValidateUtil.isAbsList(list)) {
                return AjaxResult.successResult(list, totalCount);
            }
//        if (ValidateUtil.isAbsList(list)) {
//            return AjaxResult.successResult(totalCount, list.size(), list);
//        }
        }
        return AjaxResult.successResult(0, 0, null);
    }

    // 团购卷统计情况
    @RequestMapping("admin/order/group/statistics")
    @ResponseBody
    public String shopTradeStatis(String token, String province, String city, String county, String username, Long shopId, Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        if (user.getUserType() == UserType.COMPANY) {
            user.setUserType(UserType.ADMIN);
            String t = SysCityCompanyMan.getSysCompanyOwnUsername(user.getUsername());
            if (StringUtils.isEmpty(t)) {
                return AjaxResult.successResult(Collections.EMPTY_LIST, 0);
            }
            user.setUsername(t);
        }

        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 12;
        }
        String sql = " FROM " + PojoTables.OrderInfo + " ori  " +
                "LEFT JOIN " + PojoTables.OrderPay + " orp ON ori.orderNo = orp.orderNo AND orp.delFlag=0 " +
//                (StringUtils.isNotEmpty(username) ? (" LEFT JOIN shop_agent_relation AS sar ON sar.shopId=ori.shopId and sar.delFlag=0 ") : "") +
                (StringUtils.isNotEmpty(username) ? (" LEFT JOIN " + PojoTables.USER_AGENT_RELATION + " AS uar ON uar.agentId=ori.agentId and uar.delFlag=0 ") : "") +
                " WHERE ori.isRefundApply !=2 AND ori.delFlag=0 and ori.orderStatus=9 AND ori.orderType= " + ORDER_TYPE.GROUP_ORDER + " " +
                (StringUtils.isNotEmpty(city) ? (" AND ori.shopCity='" + city + "'") : "") +
                (StringUtils.isNotEmpty(county) ? (" AND si.county='" + county + "'") : "") +
                (StringUtils.isNotEmpty(username) ? (" AND uar.username='" + username + "'") : "") +
                (null != startTime && null != endTime ? (" AND ori.createtime BETWEEN " + startTime + " AND " + endTime) : "");
        String listSql = "SELECT FROM_UNIXTIME(ori.createTime/1000,'%Y-%m-%d') AS oriDate, " +
                "COUNT(ori.orderNo) totalCount, " +
                "SUM(IFNULL(ori.totalMoney,0)) totalMoney, " +
                "SUM(CASE WHEN ori.orderStatus=9 THEN 1 ELSE 0 END) useCount, " +
                "SUM(CASE WHEN ori.orderStatus=9 THEN IFNULL(ori.totalMoney,0) ELSE 0 END) useMoney, " +
                "SUM(CASE WHEN ori.orderStatus!=9 THEN 1 ELSE 0 END) unuseCount, " +
                "SUM(CASE WHEN ori.orderStatus!=9 THEN IFNULL(ori.totalMoney,0) ELSE 0 END) unuseMoney, " +
                "COUNT(DISTINCT CASE WHEN ori.orderstatus=9 THEN ori.username ELSE NULL END) userCount, " +
                "SUM(CASE WHEN ori.orderStatus=9 THEN IFNULL(orp.shopMoney,0) ELSE 0 END) shopMoney, " +
                "SUM(CASE WHEN ori.orderstatus=9 THEN IFNULL(orp.platformMoney,0) ELSE 0 END) AS platformMoney ";
        String limit = " limit " + (page - 1) * size + "," + size;
        String group = " GROUP BY oriDate DESC";
        List<HashMap<String, Object>> list = null;
        List<HashMap<String, Object>> totalList = null;
        int total = 0;
        try {
            String sqlList = listSql + sql + group + limit;
            String sqlTotalList = listSql + sql;
            list = UserDaoSql.getInstance().queryBySql(sqlList);

            if (isNoCount) {
                totalList = UserDaoSql.getInstance().queryBySql(sqlTotalList);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        if (null != totalList) {
            total = totalList.size();
        }
        if (null != list) {
            JSONObject result = new JSONObject();
            result.put("status", 1);
            result.put("totalCount", total);
            result.put("data", JSONArray.fromObject(list));
            result.put("info", JSONArray.fromObject(totalList));
            return result.toString();
        }
        return AjaxResult.successResult();
    }

    // 获取押金充值订单
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/deposit_in/list")
    @ResponseBody
    public String order_admin_deposit_order(String token, String username,
                                            Long startTime, Long endTime,
                                            String orderNo,
                                            @RequestParam(defaultValue = "1") Integer page,
                                            @RequestParam(defaultValue = "20") Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }

        StringBuilder sb = new StringBuilder();
        sb.append(" from ").append(PojoTables.OrderInfo)
                .append(" where orderType =").append(ORDER_TYPE.WALLET_DEPOSIT_IN)
                .append(" and delFlag = 0 ");

        if (StringUtils.isNotEmpty(username)) {
            sb.append(" and username like '%").append(username).append("%'");
        }
        if (startTime != null) {
            sb.append(" and createTime >").append(startTime);
        }
        if (endTime != null) {
            sb.append(" and createTime <").append(endTime);
        }
        if (StringUtils.isNotEmpty(orderNo)) {
            sb.append(" and orderNo like '%").append(orderNo).append("%'");
        }
        //
        StringBuilder countSql = new StringBuilder();
        countSql.append(" select count(*) as counts ")
                .append(sb.toString());
        long count = 0L;
        StringBuilder dataSql = new StringBuilder();
        dataSql.append(" select * ").append(sb.toString())
                .append(" order by createTime desc limit ").append((page - 1) * size).append(",").append(size);
        List<OrderInfo> dataList = null;
        try {
            if (!isNoCount) {
                count = UserDaoSql.getInstance().getCount(countSql.toString());
            }

            if (ValidateUtil.isAbsLong(count) || isNoCount) {
                dataList = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, dataSql.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败,请稍后重试");
        }
        if (ValidateUtil.isAbsList(dataList)) {
            List<OrderInfoVO> infoVOS = dataList.stream().map(a -> getOrderInfo(a)).collect(Collectors.toList());
            return AjaxResult.successResult(infoVOS, count);
        }
        return AjaxResult.successResult(null, 0);
    }

    public static OrderInfoVO getOrderInfo(OrderInfo orderInfo) {
        if (orderInfo == null) {
            return null;
        }
        OrderInfoVO vo = new OrderInfoVO();
        BeanUtils.copyProperties(orderInfo, vo);
        if (StringUtils.isNotEmpty(vo.getUsername())) {
            UserInfo info = UserInfoMemory.getInstance().getUserInfo(vo.getUsername());
            if (info != null) {
                UserInfoVO infoVO = new UserInfoVO();
                BeanUtils.copyProperties(info, infoVO);
                vo.setUserInfo(infoVO);
            }
        }
        return vo;
    }

}
